Skip to content

Commit 9f24a59

Browse files
author
Joseph Luce
authored
Create 113_path_sum_II.md
1 parent d991c5a commit 9f24a59

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

leetcode/medium/113_path_sum_II.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# 113. Path Sum II
2+
3+
## Recursive Solution
4+
- Runtime: O(N)
5+
- Space: O(N)
6+
- N = Number of nodes in tree
7+
8+
There are a few things that need to be added outside of a normal traversal of a binary tree.
9+
Outside of these things, everything else is a post order traversal.
10+
11+
1. Keep track of the sum as we traverse.
12+
2. Have a result we can modify as we traverse.
13+
3. Keep track of what nodes we have already traversed for when we find a matching sum.
14+
15+
```
16+
class Solution:
17+
def pathSum(self, root: TreeNode, target: int) -> List[List[int]]:
18+
def path_sum_helper(root, target, curr_sum, result, stack):
19+
if root is None:
20+
return
21+
stack.append(root.val)
22+
curr_sum += root.val
23+
if root.left is None and root.right is None and target == curr_sum:
24+
result.append([s for s in stack])
25+
path_sum_helper(root.left, target, curr_sum, result, stack)
26+
path_sum_helper(root.right, target, curr_sum, result, stack)
27+
stack.pop()
28+
29+
result = list()
30+
path_sum_helper(root, target, 0, result, [])
31+
return result
32+
```

0 commit comments

Comments
 (0)