Given a BST and a valid range of keys, remove nodes from the BST that have keys outside the valid range.

For example, consider BST shown on the left below. It should be truncated to BST shown on the right.

 
Remove nodes from BST

Practice this problem

The idea is simple – traverse the tree in a bottom-up fashion and truncate the left and right subtree before processing a node. 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 its key falls within the valid range, nothing needs to be done.
  • If the root’s key is smaller than the minimum allowed, remove it and set the root to its right child.
  • If the root’s key is larger than the maximum allowed, remove it and set the root to its left child.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

10 12

Java


Download  Run Code

Output:

10 12

Python


Download  Run Code

Output:

10 12

The time complexity of the above solution is O(n), where n is the size of the BST, and requires space proportional to the tree’s height for the call stack.