# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param root TreeNode类
# @param sum int整型
# @return bool布尔型
class Solution:
def hasPathSum(self , root: TreeNode, sum: int) -> bool:
def dfs(root,res):
if root is None:return False
if root.val==res and root.left is None and root.right is None:
return True
return dfs(root.left,res-root.val) or dfs(root.right,res-root.val)
result=dfs(root,sum)
return result
这样是正确的
def hasPathSum(self , root: TreeNode, sum: int) -> bool:
def dfs(root,res):
if root is None:return False
if root.val==res and root.left is None and root.right is None:
return True
if root.left:
return dfs(root.left,res-root.val)
if root.right:
return dfs(root.right,res-root.val)
result=dfs(root,sum)
return result
这是错误的
大佬求解