方法1.还是用递归的方法实现
方法2.二叉树的层序遍历
方法3.深度优先搜索
方法1代码:
class Solution:
def hasPathSum(self , root: TreeNode, sum: int) -> bool:
# write code here
if not root:
return False
elif root.val == sum and not root.left and not root.right:
return True
left_flag = self.hasPathSum(root.left, sum - root.val)
right_flag = self.hasPathSum(root.right, sum - root.val)
return left_flag or right_flag