Skip to content

Commit 745a0e5

Browse files
author
Joseph Luce
authored
Update 112_path_sum.md
1 parent ef4e635 commit 745a0e5

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

leetcode/easy/112_path_sum.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,29 @@ class Solution:
2626
2727
return has_path_sum_helper(root, 0, sum)
2828
```
29+
30+
## Iterative Solution
31+
- Runtime: O(N)
32+
- Space: O(N)
33+
- N = Number of nodes in tree
34+
35+
Similar to the recursive solution, but we need to store an additional current sum with the node in the stack.
36+
Since we will never need to go back up the tree once we have traverse down, there is no need to implement a global sum.
37+
38+
```
39+
class Solution:
40+
def hasPathSum(self, root: TreeNode, target: int) -> bool:
41+
stack = list([(root, 0)])
42+
while len(stack) > 0:
43+
curr_node, curr_sum = stack.pop()
44+
if curr_node is None:
45+
continue
46+
curr_sum += curr_node.val
47+
if curr_node.left is None and curr_node.right is None:
48+
if curr_sum == target:
49+
return True
50+
continue
51+
stack.append((curr_node.right, curr_sum))
52+
stack.append((curr_node.left, curr_sum))
53+
return False
54+
```

0 commit comments

Comments
 (0)