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
- Remove elements from the array whose frequency lies in the range [l, r]
- Queries for elements having values within the range A to B in the given index range using Segment Tree
- Binary Indexed Tree : Range Update and Range Queries
- Construct all possible BSTs for keys 1 to N
- BST to a Tree with sum of all smaller keys
- Windows Shortcut Keys
- Introduction to SSH(Secure Shell) Keys
- Range and Coefficient of range of Array
- Merge two arrays keeping original keys in PHP
- Handling missing keys in Python dictionaries
- Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
- Total number of possible Binary Search Trees and Binary Trees with n keys
- How to remove the first character of string in PHP?
- Remove new lines from string in PHP
- Remove characters that appear more than k times
- Program to remove consonants from a String
- Remove elements from the array which appear more than k times
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.