Given a binary tree and a number k, remove nodes from the tree which lie on a complete path having a sum less than k. A complete path in a binary tree is defined as a path from the root to a leaf. The sum of all nodes on that path is defined as the sum of that path.

A node can be part of multiple paths. So, we have to delete it only if all paths from it have a sum less than k. For example, consider the binary tree shown on the left below. Convert it into the binary tree shown on the right. Note that the deletion should be done in a bottom-up manner until the path has a root-to-leaf sum greater than or equal to k.

Truncate Binary Tree

Practice this problem

The problem might look complex at first look, but its solution is simple. The idea is to traverse the tree in a bottom-up fashion and truncate the left and right subtree before processing its parent. Since we are doing a postorder traversal, the subtree rooted at the current node may be truncated, and the current node becomes a leaf node now. So, for each node, check

  • If the sum of nodes in the path from the root node to the current node is more than or equal to k, nothing needs to be done.
  • If it is a leaf node and its path from the root node has a sum less than k, remove it.

Following is the C++, Java, and Python implementation based on the above idea:

C++


Download  Run Code

Output:

6 4 7 8

Java


Download  Run Code

Output:

6 4 7 8

Python


Download  Run Code

Output:

6 4 7 8

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The program requires O(h) extra space for the call stack, where h is the height of the tree.