437. Path Sum III
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/\ \
3 2 11
/ \ \
3 -2 1
Return 3. The paths that sum to 8 are:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11Thoughts:
DFS recursion: T: O(N^2) 1. Find the root.left and root.right: (base case: for root == null; return 0) 2. if (both left and right ==0)-> leaf node, then return 1, 3. if only left == 0: have to return right + 1 4. if only right == 0; have to return left + 1 5. if both left and right != 0; then return the min(left,right) + 1 6. Merge sort : T: T(N) = N + 2T(N/2) = O(NlogN) or O(N^2) for worse complexity (unbalanced tree)
Two Sum Method: Hash table: T: O(n) S: O(n):
As we traverse down the tree, at an arbitrary node N, we store the sum until this node N (sum_so_far (prefix) + N.val). in hash-table. Note this sum is the sum from root to N.
Now at a grand-child of N, say G, we can compute the sum from the root until G since we have the prefix_sum until this grandchild available.We pass in our recursive routine.
Search for prefixSum + node.val - target for the predecessor
Once done with a node and all its grandchildren, we remove it from the hash-table. This makes sure that the number of complement paths returned always correspond to paths that ended(started) at a predecessor node.
Code: DFS Recursion O(N^2)
Code: Python
Code: Two-Sum: HashTable: T: O(n) S: O(n)
Last updated
Was this helpful?