Tree — Path Sum

      5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
sum_to_end = 0
stack = [(root, 0)]
found = False

while stack and not found:

node, current_value = stack.pop()

if node:
current_value = current_value + node.val
if not node.left and not node.right:
if current_value == sum:
found = True
current_value = 0
else:
stack.append((node.left, current_value))
stack.append((node.right, current_value))

return found

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store