给定一棵二叉树和一个总和,确定该树中是否存在根到叶的路径,这条路径的所有值相加等于给定的总和。
例如:
给定下面的二叉树和 总和 = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
返回 true
, 因为存在总和为 22 的根到叶的路径 5->4->11->2
。
解题思路:
从左往右搜索到最深处即可
解题代码:
from collections import deque
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root:
queue = deque([(root, root.val)])
while queue:
p, s = queue.popleft()
left, right = p.left, p.right
if left:
queue.append((p.left, s + p.left.val))
if right:
queue.append((p.right, s + p.right.val))
if not left and not right and s == sum:
return True
return False
return False
注意:判断条件的地方只能用right和left,不能为p.left or p.right