Open In App

Remove BST keys outside the given range

Last Updated : 21 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Search Tree (BST) and a range [min, max], the task is to remove all keys which are outside the given range. The modified tree should also be BST. 

Examples:

Input : low = -10, high = 13

remove-bst-keys-outside-the-given-range

 Output: 

remove-bst-keys-outside-the-given-range-2

Explanation: All keys outside the range [-10, 13] are removed and the modified tree is BST. 

Approach:

The idea is to recursively traverse the BST. For each node, process the left and right subtree recursively and get the updated left and right nodes. If the current node lies in the range, then update the left and right nodes and return the current node. If the current node is less than given range, then return the updated right node. Otherwise, return the updated left node.

Step by step approach:

  • For a given node root, first recursively process the left and right subtrees.
  • There are three possibilities:
    • If the root node lies in the given range, then update its root'left and root'right to left and right respectively. Return the root node.
    • If the root node is less than range, then return the right node.
    • Else return the left node.

Below is the implementation of the above approach:

C++
// C++ program to print BST
// in a given range
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;
    Node (int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Function to remove keys that do not 
// lie in the given range.
Node* removekeys(Node* root, int l, int r) {
    
    // base case
    if (root == nullptr) return nullptr;
    
    // Process the left subtree and get the
    // updated left node.
    Node* left = removekeys(root->left, l, r);
    
    // Process the right subtree and get the
    // updated right node.
    Node* right = removekeys(root->right, l ,r);
    
    // If curr node lies in the range, update its 
    // left and right nodes and return curr node.
    if (root->data>=l && root->data<=r) {
        root->left = left;
        root->right = right;
        
        return root;
    }
    
    // If current node is less than range,
    // then return the updated right subtree.
    else if (root->data<l) {
        return right;
    }
    
    // Else return the updated left subtree.
    else 
        return left;
}

void printInorder(Node* root) {
    if (root == nullptr) return;
    
    printInorder(root->left);
    cout << root->data << " ";
    printInorder(root->right);
}

int main() {
    
    // BST
    //          6
    //       /    \
    //     -13     14
    //       \    /  \
    //       -8 13    15
    //         /
    //        7
    Node* root = new Node(6);
    root->left = new Node(-13);
    root->right = new Node(14);
    root->left->right = new Node(-8);
    root->right->left = new Node(13);
    root->right->right = new Node(15);
    root->right->left->left = new Node(7);
    int low = -10, high = 13;
    
    Node* ans = removekeys(root, low, high);
    printInorder(ans);
    
    return 0;
}
Java
// Java program to print BST
// in a given range

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Function to remove keys that do not 
    // lie in the given range.
    static Node removekeys(Node root, int l, int r) {

        // base case
        if (root == null) return null;

        // Process the left subtree and get the
        // updated left node.
        Node left = removekeys(root.left, l, r);

        // Process the right subtree and get the
        // updated right node.
        Node right = removekeys(root.right, l ,r);

        // If curr node lies in the range, update its 
        // left and right nodes and return curr node.
        if (root.data >= l && root.data <= r) {
            root.left = left;
            root.right = right;

            return root;
        }

        // If current node is less than range,
        // then return the updated right subtree.
        else if (root.data < l) {
            return right;
        }

        // Else return the updated left subtree.
        else {
            return left;
        }
    }

    static void printInorder(Node root) {
        if (root == null) return;

        printInorder(root.left);
        System.out.print(root.data + " ");
        printInorder(root.right);
    }

    public static void main(String[] args) {

        // BST
        //          6
        //       /    \
        //     -13     14
        //       \    /  \
        //       -8  13   15
        //         /
        //        7
        Node root = new Node(6);
        root.left = new Node(-13);
        root.right = new Node(14);
        root.left.right = new Node(-8);
        root.right.left = new Node(13);
        root.right.right = new Node(15);
        root.right.left.left = new Node(7);

        int low = -10, high = 13;

        Node ans = removekeys(root, low, high);
        printInorder(ans);
    }
}
Python
# Python program to print BST
# in a given range

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Function to remove keys that do not 
# lie in the given range.
def removekeys(root, l, r):

    # base case
    if root is None:
        return None

    # Process the left subtree and get the
    # updated left node.
    left = removekeys(root.left, l, r)

    # Process the right subtree and get the
    # updated right node.
    right = removekeys(root.right, l, r)

    # If curr node lies in the range, update its 
    # left and right nodes and return curr node.
    if l <= root.data <= r:
        root.left = left
        root.right = right
        return root

    # If current node is less than range,
    # then return the updated right subtree.
    elif root.data < l:
        return right

    # Else return the updated left subtree.
    else:
        return left

def printInorder(root):
    if root is None:
        return
    printInorder(root.left)
    print(root.data, end=" ")
    printInorder(root.right)

if __name__ == "__main__":
    
    # BST
    #          6
    #       /    \
    #     -13     14
    #       \    /  \
    #       -8  13   15
    #         /
    #        7
    root = Node(6)
    root.left = Node(-13)
    root.right = Node(14)
    root.left.right = Node(-8)
    root.right.left = Node(13)
    root.right.right = Node(15)
    root.right.left.left = Node(7)

    low, high = -10, 13
    ans = removekeys(root, low, high)
    printInorder(ans)
C#
// C# program to print BST
// in a given range

using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Function to remove keys that do not 
    // lie in the given range.
    static Node removekeys(Node root, int l, int r) {

        // base case
        if (root == null) return null;

        // Process the left subtree and get the
        // updated left node.
        Node left = removekeys(root.left, l, r);

        // Process the right subtree and get the
        // updated right node.
        Node right = removekeys(root.right, l ,r);

        // If curr node lies in the range, update its 
        // left and right nodes and return curr node.
        if (root.data >= l && root.data <= r) {
            root.left = left;
            root.right = right;

            return root;
        }

        // If current node is less than range,
        // then return the updated right subtree.
        else if (root.data < l) {
            return right;
        }

        // Else return the updated left subtree.
        else {
            return left;
        }
    }

    static void printInorder(Node root) {
        if (root == null) return;

        printInorder(root.left);
        Console.Write(root.data + " ");
        printInorder(root.right);
    }

    static void Main(string[] args) {

        // BST
        //          6
        //       /    \
        //     -13     14
        //       \    /  \
        //       -8  13   15
        //         /
        //        7
        Node root = new Node(6);
        root.left = new Node(-13);
        root.right = new Node(14);
        root.left.right = new Node(-8);
        root.right.left = new Node(13);
        root.right.right = new Node(15);
        root.right.left.left = new Node(7);

        int low = -10, high = 13;

        Node ans = removekeys(root, low, high);
        printInorder(ans);
    }
}
JavaScript
// JavaScript program to print BST
// in a given range

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function to remove keys that do not 
// lie in the given range.
function removekeys(root, l, r) {

    // base case
    if (root === null) return null;

    // Process the left subtree and get the
    // updated left node.
    let left = removekeys(root.left, l, r);

    // Process the right subtree and get the
    // updated right node.
    let right = removekeys(root.right, l, r);

    // If curr node lies in the range, update its 
    // left and right nodes and return curr node.
    if (root.data >= l && root.data <= r) {
        root.left = left;
        root.right = right;
        return root;
    }

    // If current node is less than range,
    // then return the updated right subtree.
    else if (root.data < l) {
        return right;
    }

    // Else return the updated left subtree.
    else {
        return left;
    }
}

function printInorder(root) {
    if (root === null) return;

    printInorder(root.left);
    console.log(root.data);
    printInorder(root.right);
}

// BST
//          6
//       /    \
//     -13     14
//       \    /  \
//       -8  13   15
//         /
//        7
let root = new Node(6);
root.left = new Node(-13);
root.right = new Node(14);
root.left.right = new Node(-8);
root.right.left = new Node(13);
root.right.right = new Node(15);
root.right.left.left = new Node(7);

let low = -10, high = 13;

let ans = removekeys(root, low, high);
printInorder(ans);

Output
-8 6 7 13 

Time Complexity: O(n), where n is the number of nodes in BST.
Auxiliary Space: O(h), where h is the height of the BST.


Next Article
Article Tags :
Practice Tags :

Similar Reads