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
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.
- Remove BST keys outside the given range
- Print BST keys in the given range
- Print BST keys in given Range | O(1) Space
- Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
- BST to a Tree with sum of all smaller keys
- K'th Largest Element in BST when modification to BST is not allowed
- Convert a normal BST to Balanced BST
- Two nodes of a BST are swapped, correct the BST | Set-2
- Two nodes of a BST are swapped, correct the BST
- Find k-th smallest element in BST (Order Statistics in BST)
- Count BST nodes that lie in a given range
- Count BST subtrees that lie in given range
- Queries for elements having values within the range A to B in the given index range using Segment Tree
- Find the largest BST subtree in a given Binary Tree | Set 1
- Sorted order printing of a given array that represents a BST
- Construct BST from given preorder traversal | Set 2
- Find a pair with given sum in a Balanced BST
- Add all greater values to every node in a given BST
- Construct BST from its given level order traversal
- Find a pair with given sum in BST
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.