Remove all nodes which lie on a path having sum less than k
Last Updated : 23 Jul, 2025
Given a binary tree,a complete path is defined as a path from a root to a leaf. The sum of all nodes on that path is defined as the sum of that path. Given the number k, the task is to remove all nodes that lie on a path with a sum less than k.
Note: A node can be part of multiple paths. So we have to delete it only in case when all paths from it have a sum less than k.
Explanation: Nodes with values 8 and 6 are deleted because the path sum from root to node with value 8 is 15 and the path sum from root to node with value 6 is 10.
Approach:
The idea is to traverse the binary tree recursively. At each node, decrement the required sum of the path. At the end of paths, check if the sum is less than equal to 0. If it is yes, then return true (meaning this path has sum >= k). Else return false. For the nodes, if false is returned by left and right subtree, then delete the current node and return false. If false is returned by only one subtree, then set the corresponding pointer to null. Then return true.
Below is the implementation of the above approach:
Output
2 5 1
Time Complexity: O(n), where n is the number of nodes. Auxiliary Space: O(h),where h is the height of the tree.