Remove BST Keys in a given Range
Given a Binary Search Tree (BST) and a range [min, max], remove all keys which are inside the given range. The modified tree should also be BST. For example, consider the following BST and range [50, 70].
50 / \ 30 70 / \ / \ 20 40 60 80 The given BST should be transformed to this: 80 / 30 / \ 20 40
There are two possible cases for every node.
1) Node’s key is inside the given range.
2) Node’s key is out of range.
We don’t need to do anything for case 2. In case 1, we need to remove the node and change the root of sub-tree rooted with this node.
The idea is to fix the tree in Postorder fashion. When we visit a node, we make sure that its left and right sub-trees are already fixed. When we find a node inside the range we call normal BST delete function to delete that node.
Following is the implementation of the above approach.
Inorder Before deletion: 20 30 40 50 60 70 80 Inorder After deletion: 20 30 40 80