感谢您的更正,我已经做了修改,但还有一个问题我无法解决:
class Solution:
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
if not root:
return False
if not root.left and not root.right:
if root.val ==targetSum:
return True
else:
return False
remainingSum = targetSum - root.val
def dfs(remainingSum, root):
dfs(remainingSum - root.left.val, root.left)
dfs(remainingSum - root.right.val, root.right)
if remainingSum == 0:
return True
return dfs(remainingSum, root)
在递归函数中,我返回什么?或者上面的代码现在正确了吗
首先,关于两个
return
语句,您是对的:第二个
return
语句不可能被执行。让我们看一下节目的其余部分。首先,逻辑应该是什么hasPathSum
检查root
是否计算为True
,如果不是,则返回False
。这很好李>targetSum
值,因为如果等于,我们可以立即返回True
。但是,您的程序会立即从targetSum
中减去根节点的值,从而产生remainingSum
,并且您永远不会检查targetSum
。想象一下,一棵树只包含一个根,没有叶,其值为5
,我们调用hasPathSum
,将targetSum
设置为5。我们应该返回True
。请记住:Aleaf是一个没有子节点的节点<因此,这棵树的根也是一片叶子,应该检查一下李>remainingSum
的hasPathSum
。如果返回值为True
,则返回True
。(无需首先检查左树值是否与if root.left:
一起存在,因为当您递归调用hasPathSum
时,它已经在检查if not root:
)remainingSum
的右树上调用hasPathSum
得到的值李>dfs
函数李>如果您只是使用
TreeNode
构造函数来创建和初始化树节点,那么您将“自下而上”创建节点,即在其父节点之前离开。例如:dfs
的结果李>dfs
函数的退出条件错误,则需要在运行到下一个dfs之前检查remainingSum
李>remainingSum
,而不是return None
李>代码:
结果:
相关问题 更多 >
编程相关推荐