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