# 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
queue = collections.deque([(root, root.val)])
while queue:
cur_node, cur_val = queue.popleft()
if cur_node.left is None and cur_node.right is None:
if cur_val == sum:
return True
if cur_node.left:
queue.append((cur_node.left, cur_val + cur_node.left.val))
if cur_node.right:
queue.append((cur_node.right, cur_val + cur_node.right.val))
return False
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if root is None:
return False
if root.left is None and root.right is None and root.val == sum:
return True
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)