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
- 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]
- BST to a Tree with sum of all smaller keys
- Construct all possible BSTs for keys 1 to N
- Binary Indexed Tree : Range Update and Range Queries
- 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
- Range and Coefficient of range of Array
- Total number of possible Binary Search Trees and Binary Trees with n keys
- How to remove the first character of string in PHP?
- Remove characters that appear more than k times
- Remove new lines from string in PHP
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.
Improved By : andrew1234