File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff 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+ ```
You can’t perform that action at this time.
0 commit comments