You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: leetcode/easy/112_path_sum.md
+32-2Lines changed: 32 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -27,13 +27,16 @@ class Solution:
27
27
return has_path_sum_helper(root, 0, sum)
28
28
```
29
29
30
-
## Iterative Solution
30
+
## Iterative Solution (Lazy Approach)
31
31
- Runtime: O(N)
32
32
- Space: O(N)
33
33
- N = Number of nodes in tree
34
34
35
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 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.
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.
0 commit comments