Remove nodes from Binary Tree such that sum of all remaining root-to-leaf paths is atleast K
Input: K = 27
Output: 5 4 8 5 6 11
Below are the paths whose sum is less than 27:
- 5 -> 3 -> 9: Path Sum = 5 + 3 + 9 = 17.
- 5 -> 4 -> 9: Path Sum = 5 + 4 + 9 = 18.
- 5 -> 4 -> 8 -> 5 -> 2: Path Sum = 5 + 4 + 8 + 5 + 2 = 24.
Below is the tree after deleting the required nodes that such that sum of all paths is at least 27:
Input: K = 10
Output: 2 1 8 12 14 7 10
- Perform the Post Order Traversal on the given Tree and during this traversal pass the sum of all nodes from the root node to each node.
- During traversal, if we reach the leaf node then check if the sum of all nodes till that node is less than K?. If found to be true, remove that node by returning the NULL node from that node.
- Repeat the above step for every leaf node encounters in the update tree.
- After the above steps, print the Preorder Traversal of the modified Tree.
Below is the implementation of the above approach:
5 4 8 5 6 11
Time Complexity: O(N), where N is the number of nodes in the given Tree.
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.