Open In App

Print BST keys in the given range

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

Given two values n1 and n2 where n1 < n2 and a root pointer to a Binary Search Tree. The task is to find all the keys of the tree in the range n1 to n2 in increasing order.

Examples:

Input: n1 = 10 , n2 = 22

print-bst-keys-in-given-range

Output: 12, 20 and 22.
Explanation: The keys are 4, 8, 12, 20, and 22, So keys in range 10 to 22 is 12, 20 and 22.

Input: n1 = 1 , n2 = 10

print-bst-keys-in-given-range

Output: 8
Explanation: The key 8 is in the range 1 to 10

Approach:

The idea is to Traverse the tree in the inorder traversal. If the Binary search tree is traversed in inorder traversal the keys are traversed in increasing order. For a given node, if the value of the root’s key is greater than n2, then recursively call in the left subtree and If node’s value is less than n1, then process the right subtree.

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;
    }
};

// Recursive function to append nodes that 
// lie in the given range.
void appendNodes(Node* root, int n1, int n2, vector<int> &ans) {
    if (root==nullptr) return;
    
    // If the curr node lies in the range, 
    // process left subtree, append curr node 
    // and process right subtree (to perform in-order)
    if (root->data >= n1 && root->data<= n2) {
        appendNodes(root->left, n1, n2, ans);
        ans.push_back(root->data);
        appendNodes(root->right, n1, n2, ans);
    }
    
    // If curr node is less than low, then
    // process right subtree.
    else if(root->data < n1) {
        appendNodes(root->right, n1, n2, ans);
    }
    
    // If curr node is greater than high, then
    // process left subtree.
    else {
        appendNodes(root->left, n1, n2, ans);
    }
}

// Main function
vector<int> printNearNodes(Node *root, int n1, int n2) {
    
    vector<int> ans;
    appendNodes(root, n1, n2, ans);
    return ans;
}

int main() {
    
    // BST
    //       22
    //      /  \
    //    12    30
    //   /  \
    //  8    20
    Node* root = new Node(22);
    root->left = new Node(12);
    root->right = new Node(30);
    root->left->left = new Node(8);
    root->left->right = new Node(20);
    int n1 = 10, n2 = 22;
    vector<int> ans = printNearNodes(root, n1, n2);
    
    for (auto num: ans) cout << num << " ";
    cout << endl;
    
    return 0;
}
Java
// Java program to print BST
// in a given range
import java.util.ArrayList;

class Node {
    int data;
    Node left, right;

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

class GfG {

    // Recursive function to append nodes that 
    // lie in the given range.
    static void appendNodes(Node root, int l, int h, 
                            ArrayList<Integer> ans) {
        if (root == null) return;

        // If the curr node lies in the range, 
        // process left subtree, append curr node 
        // and process right subtree (to perform in-order)
        if (root.data >= l && root.data <= h) {
            appendNodes(root.left, l, h, ans);
            ans.add(root.data);
            appendNodes(root.right, l, h, ans);
        }

        // If curr node is less than low, then
        // process right subtree.
        else if (root.data < l) {
            appendNodes(root.right, l, h, ans);
        }

        // If curr node is greater than high, then
        // process left subtree.
        else {
            appendNodes(root.left, l, h, ans);
        }
    }

    static ArrayList<Integer> printNearNodes(Node root, int low, int high) {
        ArrayList<Integer> ans = new ArrayList<>();
        appendNodes(root, low, high, ans);
        return ans;
    }

    public static void main(String[] args) {
        
        // BST
        //       22
        //      /  \
        //    12    30
        //   /  \
        //  8    20
        Node root = new Node(22);
        root.left = new Node(12);
        root.right = new Node(30);
        root.left.left = new Node(8);
        root.left.right = new Node(20);

        int low = 10, high = 22;
        ArrayList<Integer> ans = printNearNodes(root, low, high);

        for (int num : ans) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}
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

# Recursive function to append nodes that 
# lie in the given range.
def appendNodes(root, l, h, ans):
    if root is None:
        return
    
    # If the curr node lies in the range, 
    # process left subtree, append curr node 
    # and process right subtree (to perform in-order)
    if l <= root.data <= h:
        appendNodes(root.left, l, h, ans)
        ans.append(root.data)
        appendNodes(root.right, l, h, ans)
    
    # If curr node is less than low, then
    # process right subtree.
    elif root.data < l:
        appendNodes(root.right, l, h, ans)
    
    # If curr node is greater than high, then
    # process left subtree.
    else:
        appendNodes(root.left, l, h, ans)

def printNearNodes(root, low, high):
    ans = []
    appendNodes(root, low, high, ans)
    return ans

if __name__ == "__main__":
    
    # BST
    #       22
    #      /  \
    #    12    30
    #   /  \
    #  8    20
    root = Node(22)
    root.left = Node(12)
    root.right = Node(30)
    root.left.left = Node(8)
    root.left.right = Node(20)

    low, high = 10, 22
    ans = printNearNodes(root, low, high)

    print(" ".join(map(str, ans)))
C#
// C# prgram to print BST
// in a given range
using System;
using System.Collections.Generic;

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

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

class GfG {
    
    // Recursive function to append nodes that 
    // lie in the given range.
    static void appendNodes(Node root, int l, int h, 
                            List<int> ans) {
        if (root == null) return;

        // If the curr node lies in the range, 
        // process left subtree, append curr node 
        // and process right subtree (to perform in-order)
        if (root.data >= l && root.data <= h) {
            appendNodes(root.left, l, h, ans);
            ans.Add(root.data);
            appendNodes(root.right, l, h, ans);
        }

        // If curr node is less than low, then
        // process right subtree.
        else if (root.data < l) {
            appendNodes(root.right, l, h, ans);
        }

        // If curr node is greater than high, then
        // process left subtree.
        else {
            appendNodes(root.left, l, h, ans);
        }
    }

    static List<int> printNearNodes(Node root, int low, int high) {
        List<int> ans = new List<int>();
        appendNodes(root, low, high, ans);
        return ans;
    }

    static void Main(string[] args) {
        
        // BST
        //       22
        //      /  \
        //    12    30
        //   /  \
        //  8    20
        Node root = new Node(22);
        root.left = new Node(12);
        root.right = new Node(30);
        root.left.left = new Node(8);
        root.left.right = new Node(20);

        int low = 10, high = 22;
        List<int> ans = printNearNodes(root, low, high);

        foreach (int num in ans) {
            Console.Write(num + " ");
        }
        Console.WriteLine();
    }
}
JavaScript
// JavaScript prgram to print BST
// in a given range

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

// Recursive function to append nodes that 
// lie in the given range.
function appendNodes(root, l, h, ans) {
    if (root === null) return;

    // If the curr node lies in the range, 
    // process left subtree, append curr node 
    // and process right subtree (to perform in-order)
    if (root.data >= l && root.data <= h) {
        appendNodes(root.left, l, h, ans);
        ans.push(root.data);
        appendNodes(root.right, l, h, ans);
    }

    // If curr node is less than low, then
    // process right subtree.
    else if (root.data < l) {
        appendNodes(root.right, l, h, ans);
    }

    // If curr node is greater than high, then
    // process left subtree.
    else {
        appendNodes(root.left, l, h, ans);
    }
}

function printNearNodes(root, low, high) {
    let ans = [];
    appendNodes(root, low, high, ans);
    return ans;
}
    
// BST
//       22
//      /  \
//    12    30
//   /  \
//  8    20
let root = new Node(22);
root.left = new Node(12);
root.right = new Node(30);
root.left.left = new Node(8);
root.left.right = new Node(20);

let low = 10, high = 22;
let ans = printNearNodes(root, low, high);

console.log(ans.join(" "));

Output
12 20 22 

Time Complexity: O(n), where n is the total number of keys in the tree.
Auxiliary Space: O(h). where h is the height of the tree.

Related article:



Next Article

Similar Reads