|
| 1 | +# 112. Path Sum |
| 2 | + |
| 3 | +## Brute Force Recursive Solution |
| 4 | +- Runtime: O(3^N) |
| 5 | +- Space: O(3^N) |
| 6 | +- N = Number of nodes in tree |
| 7 | + |
| 8 | +Thinking about the brute force method, for every node in the tree, traverse their left child and right child to find the target sum. |
| 9 | +Due to the natural of the problem, we have to traverse all the nodes down the path until we reach a leaf node. |
| 10 | +After we know the number of paths for the left child and right child, we have to repeat what we did but now the left child is the parent and again for the right child as parent. |
| 11 | +Because of this, we need to keep a visited set to make sure we don't add duplicate paths. |
| 12 | +This is similar to a DFS implementation. |
| 13 | + |
| 14 | +The runtime can be calculated in this way. |
| 15 | +For each recursive call, we want to traverse the left and right children down to the leaf nodes, this is O(N) runtime. |
| 16 | +Since we would have to do this again but for the left and right children, it about O(N-1) for each. |
| 17 | +So we basically have O(N) three times which means O(3^N). |
| 18 | + |
| 19 | +Remember the formula for recursion, (Number of calls ^ (Big O per call)) |
| 20 | + |
| 21 | +``` |
| 22 | +class Solution: |
| 23 | + def pathSum(self, root: TreeNode, target: int) -> int: |
| 24 | + def path_sum_helper(root, curr_sum, target, parent, visited): |
| 25 | + if root is None: |
| 26 | + return 0 |
| 27 | + curr_sum += root.val |
| 28 | + n_paths = 0 |
| 29 | + if curr_sum == target and (parent, root) not in visited: |
| 30 | + visited.add((parent, root)) |
| 31 | + n_paths += 1 |
| 32 | + n_paths += path_sum_helper(root.left, curr_sum, target, parent, visited) |
| 33 | + n_paths += path_sum_helper(root.right, curr_sum, target, parent, visited) |
| 34 | + n_paths += path_sum_helper(root.left, 0, target, root.left, visited) |
| 35 | + n_paths += path_sum_helper(root.right, 0, target, root.right, visited) |
| 36 | + return n_paths |
| 37 | + |
| 38 | + return path_sum_helper(root, 0, target, parent=root, visited=set()) |
| 39 | +``` |
0 commit comments