Dynamic Programming is a technique to solve problems by breaking them down into overlapping sub-problems which follows the optimal substructure. There are various problems using DP like subset sum, knapsack, coin change etc. DP can also be applied to trees to solve some specific problems. Given a binary tree with n nodes and n-1 edges, calculate the maximum sum of the node values from the root to any of the leaves without re-visiting any node.
Output: 22 Explanation: Given above is a diagram of a tree with n = 14 nodes and n-1 = 13 edges.The below shows all the paths from root to leaves:
3 -> 2 -> 1 -> 4: sum of all node values = 10
3 -> 2 -> 1 -> 5: sum of all node values = 11
3 -> 2 -> 3: sum of all node values = 8
3 -> 1 -> 9 -> 9: sum of all node values = 22
3 -> 1 -> 9 -> 8 : sum of all node values = 21
3 -> 10 -> 1: sum of all node values = 14
3 -> 10 -> 5 : sum of all node values = 18
3 -> 10 -> 3 : sum of all node values = 16
The answer is 22, as Path 4 has the maximum sum of values of nodes in its path from a root to leaves.
The greedy approach fails in this case. Starting from the root andtake 3 from the first level, 10 from the next level and 5 from the third level greedily. Result is path -7 if after following the greedy approach, hence do not apply greedy approach over here.
Using Recursion - O(n) Time and O(h) Space
For the recursive approach, the task is to calculate the maximum sum from the root to any leaf node. At each node, there are two cases:
Add the value of the current node to the currentSum and proceed to its left and right children recursively.
If the node is a leaf (both left and right children are null), compare the currentSum with the maxSum. Update maxSum if currentSum is greater.
Mathematically, the recurrence relation can be expressed as:
If the current node is nullptr, return from the recursion (no addition to the sum is possible).
Output
10
Using Top-Down DP (Memoization) - O(n) Time and O(n) Space
1. Optimal Substructure: The solution to the maximum sum problem can be derived from the optimal solutions of smaller subproblems. At any given node, the maximum path sum is the sum of the nodeβs value and the maximum of the sums obtained from its left and right children.
2. Overlapping Subproblems: The maximum sum for a node may be recomputed multiple times. Using a memoization table we:
Check if the result for a node exists.If not, compute and store it.
This avoids redundant calculations and ensures each node is processed once.
Memoization Condition: If the result for the current node is already stored in the memoization table: