Remove BST keys outside the given range - GeeksforGeeks

25 May, 2021
Given a Binary Search Tree (BST) and a range [min, max], remove all keys which are outside the given range. The modified tree should also be BST. For example, consider the following BST and range [-10, 13].  
The given tree should be changed to the following. Note that all keys outside the range [-10, 13] are removed and the modified tree is BST.  
There are two possible cases for every node. 1) Node’s key is outside the given range. This case has two sub-cases. .......a) Node’s key is smaller than the min value. .......b) Node’s key is greater than the max value. 2) Node’s key is in 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 the subtree rooted with this node. 
The idea is to fix the tree in a Post-order fashion. When we visit a node, we make sure that its left and right sub-trees are already fixed. In case 1.a), we simply remove the root and return the right sub-tree as a new root. In case 1.b), we remove the root and return the left sub-tree as a new root.
Following is the implementation of the above approach. 
C++
Java
Python3
C#
Javascript
// A C++ program to remove BST keys outside the given range#include<bits/stdc++.h> using namespace std; // A BST node has key, and left and right pointersstruct node{    int key;    struct node *left;    struct node *right;}; // Removes all nodes having value outside the given range and returns the root// of modified treenode* removeOutsideRange(node *root, int min, int max){   // Base Case   if (root == NULL)      return NULL;    // First fix the left and right subtrees of root   root->left =  removeOutsideRange(root->left, min, max);   root->right =  removeOutsideRange(root->right, min, max);    // Now fix the root.  There are 2 possible cases for root   // 1.a) Root's key is smaller than min value (root is not in range)   if (root->key < min)   {       node *rChild = root->right;       delete root;       return rChild;   }   // 1.b) Root's key is greater than max value (root is not in range)   if (root->key > max)   {       node *lChild = root->left;       delete root;       return lChild;   }   // 2. Root is in range   return root;} // A utility function to create a new BST node with key as given numnode* newNode(int num){    node* temp = new node;    temp->key = num;    temp->left = temp->right = NULL;    return temp;} // A utility function to insert a given key to BSTnode* insert(node* root, int key){    if (root == NULL)       return newNode(key);    if (root->key > key)       root->left = insert(root->left, key);    else       root->right = insert(root->right, key);    return root;} // Utility function to traverse the binary tree after conversionvoid inorderTraversal(node* root){    if (root)    {        inorderTraversal( root->left );        cout << root->key << " ";        inorderTraversal( root->right );    }} // Driver program to test above functionsint main(){    node* root = NULL;    root = insert(root, 6);    root = insert(root, -13);    root = insert(root, 14);    root = insert(root, -8);    root = insert(root, 15);    root = insert(root, 13);    root = insert(root, 7);     cout << "Inorder traversal of the given tree is: ";    inorderTraversal(root);     root = removeOutsideRange(root, -10, 13);     cout << "\nInorder traversal of the modified tree is: ";    inorderTraversal(root);     return 0;}
// A Java program to remove BST// keys outside the given rangeimport java.math.BigDecimal;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Scanner; class Node{    int key;    Node left;    Node right;} class GFG{    // Removes all nodes having value    // outside the given range and    // returns the root of modified tree    private static Node removeOutsideRange(Node root,                                           int min, int max)    {        // BASE CASE        if(root == null)        {            return null;        }                 // FIRST FIX THE LEFT AND        // RIGHT SUBTREE OF ROOT        root.left = removeOutsideRange(root.left,                                       min, max);        root.right = removeOutsideRange(root.right,                                        min, max);                 // NOW FIX THE ROOT. THERE ARE        // TWO POSSIBLE CASES FOR THE ROOT        // 1. a) Root's key is smaller than        // min value(root is not in range)        if(root.key < min)        {            Node rchild = root.right;            root = null;            return rchild;        }                 // 1. b) Root's key is greater than        // max value (Root is not in range)        if(root.key > max)        {            Node lchild = root.left;            root = null;            return lchild;        }                 // 2. Root in range        return root;    }     public static Node newNode(int num)    {        Node temp = new Node();        temp.key = num;        temp.left = null;        temp.right = null;        return temp;    }     public static Node insert(Node root,                              int key)    {        if(root == null)        {            return newNode(key);        }        if(root.key > key)        {            root.left = insert(root.left, key);        }        else        {            root.right = insert(root.right, key);        }        return root;    }         private static void inorderTraversal(Node root)    {        if(root != null)        {            inorderTraversal(root.left);            System.out.print(root.key + " ");            inorderTraversal(root.right);        }    }         // Driver code    public static void main(String[] args)    {        Node root = null;        root = insert(root, 6);        root = insert(root, -13);        root = insert(root, 14);        root = insert(root, -8);        root = insert(root, 15);        root = insert(root, 13);        root = insert(root, 7);                 System.out.print("Inorder Traversal of " +                           "the given tree is: ");        inorderTraversal(root);                 root = removeOutsideRange(root, -10, 13);                 System.out.print("\nInorder traversal of " +                           "the modified tree: ");        inorderTraversal(root);    }} // This code is contributed// by Divya
# Python3 program to remove BST keys# outside the given range # A BST node has key, and left and right # pointers. A utility function to create# a new BST node with key as given numclass newNode:     # Constructor to create a new node    def __init__(self, data):        self.key = data        self.left = None        self.right = None         # Removes all nodes having value outside# the given range and returns the root# of modified treedef removeOutsideRange(root, Min, Max):         # Base Case    if root == None:        return None         # First fix the left and right    # subtrees of root    root.left = removeOutsideRange(root.left,                                   Min, Max)    root.right = removeOutsideRange(root.right,                                    Min, Max)         # Now fix the root. There are 2    # possible cases for root    # 1.a) Root's key is smaller than    #      min value (root is not in range)    if root.key < Min:        rChild = root.right        return rChild             # 1.b) Root's key is greater than max    #      value (root is not in range)    if root.key > Max:        lChild = root.left        return lChild             # 2. Root is in range    return root  # A utility function to insert a given# key to BSTdef insert(root, key):    if root == None:        return newNode(key)    if root.key > key:        root.left = insert(root.left, key)    else:        root.right = insert(root.right, key)    return root # Utility function to traverse the binary# tree after conversiondef inorderTraversal(root):    if root:        inorderTraversal( root.left)        print(root.key, end = " ")        inorderTraversal( root.right) # Driver Codeif __name__ == '__main__':    root = None    root = insert(root, 6)    root = insert(root, -13)    root = insert(root, 14)    root = insert(root, -8)    root = insert(root, 15)    root = insert(root, 13)    root = insert(root, 7)     print("Inorder traversal of the given tree is:",                                          end = " ")    inorderTraversal(root)     root = removeOutsideRange(root, -10, 13)    print()    print("Inorder traversal of the modified tree is:",                                             end = " ")    inorderTraversal(root) # This code is contributed by PranchalK
// A C# program to remove BST// keys outside the given rangeusing System; public class Node{    public int key;    public Node left;    public Node right;} public class GFG{    // Removes all nodes having value    // outside the given range and    // returns the root of modified tree    private static Node removeOutsideRange(Node root,                                        int min, int max)    {        // BASE CASE        if(root == null)        {            return null;        }                 // FIRST FIX THE LEFT AND        // RIGHT SUBTREE OF ROOT        root.left = removeOutsideRange(root.left,                                    min, max);        root.right = removeOutsideRange(root.right,                                        min, max);                 // NOW FIX THE ROOT. THERE ARE        // TWO POSSIBLE CASES FOR THE ROOT        // 1. a) Root's key is smaller than        // min value(root is not in range)        if(root.key < min)        {            Node rchild = root.right;            root = null;            return rchild;        }                 // 1. b) Root's key is greater than        // max value (Root is not in range)        if(root.key > max)        {            Node lchild = root.left;            root = null;            return lchild;        }                 // 2. Root in range        return root;    }     public static Node newNode(int num)    {        Node temp = new Node();        temp.key = num;        temp.left = null;        temp.right = null;        return temp;    }     public static Node insert(Node root,                            int key)    {        if(root == null)        {            return newNode(key);        }        if(root.key > key)        {            root.left = insert(root.left, key);        }        else        {            root.right = insert(root.right, key);        }        return root;    }         private static void inorderTraversal(Node root)    {        if(root != null)        {            inorderTraversal(root.left);            Console.Write(root.key + " ");            inorderTraversal(root.right);        }    }         // Driver code    public static void Main(String[] args)    {        Node root = null;        root = insert(root, 6);        root = insert(root, -13);        root = insert(root, 14);        root = insert(root, -8);        root = insert(root, 15);        root = insert(root, 13);        root = insert(root, 7);                 Console.Write("Inorder Traversal of " +                        "the given tree is: ");        inorderTraversal(root);                 root = removeOutsideRange(root, -10, 13);                 Console.Write("\nInorder traversal of " +                        "the modified tree: ");        inorderTraversal(root);    }} // This code has been contributed// by PrinciRaj1992
<script> // A JavaScript program to remove BST// keys outside the given range  class Node {    constructor() {        this.key = 0;        this.left = null;        this.right = null;    }}// Removes all nodes having value    // outside the given range and    // returns the root of modified tree     function removeOutsideRange(root , min , max) {        // BASE CASE        if (root == null) {            return null;        }         // FIRST FIX THE LEFT AND        // RIGHT SUBTREE OF ROOT        root.left =        removeOutsideRange(root.left, min, max);        root.right =        removeOutsideRange(root.right, min, max);         // NOW FIX THE ROOT. THERE ARE        // TWO POSSIBLE CASES FOR THE ROOT        // 1. a) Root's key is smaller than        // min value(root is not in range)        if (root.key < min) {    var rchild = root.right;            root = null;            return rchild;        }         // 1. b) Root's key is greater than        // max value (Root is not in range)        if (root.key > max) {    var lchild = root.left;            root = null;            return lchild;        }         // 2. Root in range        return root;    }     function newNode(num) {var temp = new Node();        temp.key = num;        temp.left = null;        temp.right = null;        return temp;    }     function insert(root , key) {        if (root == null) {            return newNode(key);        }        if (root.key > key) {            root.left = insert(root.left, key);        } else {            root.right = insert(root.right, key);        }        return root;    }      function inorderTraversal(root) {        if (root != null) {            inorderTraversal(root.left);            document.write(root.key + " ");            inorderTraversal(root.right);        }    }     // Driver code     var root = null;        root = insert(root, 6);        root = insert(root, -13);        root = insert(root, 14);        root = insert(root, -8);        root = insert(root, 15);        root = insert(root, 13);        root = insert(root, 7);         document.write("Inorder Traversal of " +        "the given tree is: ");        inorderTraversal(root);         root = removeOutsideRange(root, -10, 13);         document.write("<br/>Inorder traversal of " +        "the modified tree: ");        inorderTraversal(root); // This code is contributed by todaysgaurav </script>
Output: 
Inorder traversal of the given tree is: -13 -8 6 7 13 14 15
Inorder traversal of the modified tree is: -8 6 7 13
Time Complexity: O(n) where n is the number of nodes in a given BST. 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
9divya5
PranchalKatiyar
princiraj1992
pravesh25pandey
todaysgaurav
Binary Search Tree
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorted Array to Balanced BST
Red-Black Tree | Set 2 (Insert)
Optimal Binary Search Tree | DP-24
Find the node with minimum value in a Binary Search Tree
Advantages of BST over Hash Table
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Difference between Binary Tree and Binary Search Tree
Lowest Common Ancestor in a Binary Search Tree.
Binary Tree to Binary Search Tree Conversion
Find k-th smallest element in BST (Order Statistics in BST)