VOOZH about

URL: https://www.geeksforgeeks.org/dsa/remove-bst-keys-outside-the-given-range/

⇱ Remove BST keys outside the given range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove BST keys outside the given range

Last Updated : 11 Oct, 2025

Given the root of a Binary Search Tree (BST) and two integers l and r, remove all the nodes whose values lie outside the range [l, r].
After modification, the resulting tree should still be a valid BST.

Examples:

Input : l = -10, r = 13

👁 file

Output: [[6], [-8, 13], [N, N, 7, N]]
Explanation: All the nodes outside the range [-10, 13] are removed and the modified tree is a valid BST. 

👁 420046835

[Naive Approach] Using Inorder Traversal - O(n) Time and O(n) Space

The idea is to traverse the BST and store all node values that lie within the given range [l, r] in sorted order (inorder traversal). Once we have this sorted list of valid values, we rebuild the BST recursively by selecting the middle element as the root, and recursively constructing the left and right subtrees from the left and right halves of the list. This ensures that the rebuilt tree contains only nodes within the range and maintains the BST property.

[Expected Approach] Using Recursion - O(n) Time and O(n) Space

The idea is to traverse the BST in post-order(LRN), At each node, we compare its value with the given range [l, r]. If the node’s value is less than l, then all nodes in its left subtree are also smaller than l due to the BST property, so we discard the left subtree and return the trimmed right subtree. Similarly, if the node’s value is greater than r, all nodes in the right subtree exceed r, so we discard the right subtree and return the trimmed left subtree. If the node’s value lies within the range, we keep it and attach the recursively trimmed left and right subtrees, ensuring that the BST property is maintained.

Why post-order?
We use post-order traversal because it allows us to trim the left and right subtrees first before processing the current node, effectively starting from the leaf nodes and moving upwards to ensure all nodes outside the given range are removed while maintaining the BST property.


Output
6 
-8 13 
N N 7 N 
Comment
Article Tags: