Skip to content

Commit 81c5f9a

Browse files
author
Joseph Luce
authored
Update 112_path_sum.md
1 parent aaf4ec3 commit 81c5f9a

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

leetcode/easy/112_path_sum.md

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,16 @@ class Solution:
2727
return has_path_sum_helper(root, 0, sum)
2828
```
2929

30-
## Iterative Solution
30+
## Iterative Solution (Lazy Approach)
3131
- Runtime: O(N)
3232
- Space: O(N)
3333
- N = Number of nodes in tree
3434

3535
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 or revisit any nodes once we have traverse down, there is no need to implement a global sum.
36+
By having both the current node and current sum at any given point, its simpliy a matter of visiting all nodes in the tree, then calculating the result.
37+
38+
I would consider this implementation "lazy", as it doesn't truely show full understanding of stacks and recursion.
39+
If you follow the traversal of this implementation, it doesn't follow any of the pre-order, in-order, or post-order traversals, since it total skips nodes and doesn't backtrack up at all.
3740

3841
```
3942
class Solution:
@@ -52,3 +55,30 @@ class Solution:
5255
stack.append((curr_node.left, curr_sum))
5356
return False
5457
```
58+
59+
60+
## Inorder Iterative Solution (Preferred Approach)
61+
62+
This implementation is similar to the above approach, however, it falls in line with how you would do an inorder traversal iteratively due to backtracking. It is important to fully understand this implementation. Try drawing it out if it confuses you, it will click better. Then try it doing pre-order and post-order traversals.
63+
64+
```
65+
class Solution:
66+
def hasPathSum(self, root: TreeNode, target: int) -> bool:
67+
stack = list()
68+
curr_node, curr_sum = root, 0
69+
while True:
70+
if curr_node is not None: # going down the tree
71+
curr_sum += curr_node.val
72+
stack.append((curr_node, curr_sum))
73+
if curr_node.left is None \
74+
and curr_node.right is None \
75+
and curr_sum == target:
76+
return True
77+
curr_node = curr_node.left
78+
elif len(stack) > 0: # going up the tree
79+
curr_node, curr_sum = stack.pop()
80+
curr_node = curr_node.right
81+
else:
82+
break
83+
return False
84+
```

0 commit comments

Comments
 (0)