给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。
解法1 递归
- 终止条件:当前节点为叶子结点 判断 节点val是否 == 更新的sum
- 递归:
- 左子树是否有指定路径?
- 右子树是否有指定路径?
- 返回 是否有指定路径?
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
if not root.left and not root.right:
return sum == root.val
left = self.hasPathSum(root.left, sum - root.val)
right = self.hasPathSum(root.right, sum - root.val)
return left or right
解法2 迭代
- 队列
- (节点, 以该节点为终点的路径总和)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
# 队列
l = [(root, root.val)]
while l:
node, val = l.pop(0)
if not node.left and not node.right and val == sum:
return True
if node.left:
l.append((node.left, val + node.left.val))
if node.right:
l.append((node.right, val + node.right.val))
return False