Skip to content

Commit e94eba7

Browse files
author
Joseph Luce
authored
Create 112_path_sum.md
1 parent bd03019 commit e94eba7

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

leetcode/easy/112_path_sum.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# 112. Path Sum
2+
3+
## Recursive Solution
4+
- Runtime: O(N)
5+
- Space: O(N)
6+
- N = Number of nodes in tree
7+
8+
Keeping track of the sum as we go down the tree is one way.
9+
So that when we reach a leaf node (no children), we can check the current sum against the target sum.
10+
Since its recursion, the current sum before the recursion call would be used so we don't need to subtract from the current sum.
11+
We let recursion do that for us.
12+
13+
Since we will be visiting all the nodes, the runtime is O(N).
14+
In the worst case, we would have to have every node on the stack if the whole tree was just a linked list, space would be O(N).
15+
16+
```
17+
class Solution:
18+
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
19+
def has_path_sum_helper(root, curr_sum, target):
20+
if root is None:
21+
return False
22+
curr_sum += root.val
23+
if root.left is None and root.right is None:
24+
return curr_sum == target
25+
return has_path_sum_helper(root.left, curr_sum, target) \
26+
or has_path_sum_helper(root.right, curr_sum, target)
27+
28+
return has_path_sum_helper(root, 0, sum)
29+
```

0 commit comments

Comments
 (0)