Open In App

Searching in Binary Search Tree (BST)

Last Updated : 21 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a BST, the task is to search a node in this BST.

For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm.  

Algorithm to search for a key in a given Binary Search Tree:

Let’s say we want to search for the number X, We start at the root. Then:

  • We compare the value to be searched with the value of the root. 
    • If it’s equal we are done with the search if it’s smaller we know that we need to go to the left subtree because in a binary search tree all the elements in the left subtree are smaller and all the elements in the right subtree are larger. 
  • Repeat the above step till no more traversal is possible
  • If at any iteration, key is found, return True. Else False.

Illustration of searching in a BST:

See the illustration below for a better understanding:

bst1

bst2

bst3

bst4

Program to implement search in BST:

C++




// C++ function to search a given key in a given BST
 
#include <iostream>
 
using namespace std;
 
struct node {
    int key;
    struct node *left, *right;
};
 
// A utility function to create a new BST node
struct node* newNode(int item)
{
    struct node* temp
        = new struct node;
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}
 
// A utility function to insert
// a new node with given key in BST
struct node* insert(struct node* node, int key)
{
    // If the tree is empty, return a new node
    if (node == NULL)
        return newNode(key);
 
    // Otherwise, recur down the tree
    if (key < node->key)
        node->left = insert(node->left, key);
    else if (key > node->key)
        node->right = insert(node->right, key);
 
    // Return the (unchanged) node pointer
    return node;
}
 
// Utility function to search a key in a BST
struct node* search(struct node* root, int key)
{
    // Base Cases: root is null or key is present at root
    if (root == NULL || root->key == key)
        return root;
 
    // Key is greater than root's key
    if (root->key < key)
        return search(root->right, key);
 
    // Key is smaller than root's key
    return search(root->left, key);
}
 
// Driver Code
int main()
{
    struct node* root = NULL;
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Key to be found
    int key = 6;
 
    // Searching in a BST
    if (search(root, key) == NULL)
        cout << key << " not found" << endl;
    else
        cout << key << " found" << endl;
 
    key = 60;
 
    // Searching in a BST
    if (search(root, key) == NULL)
        cout << key << " not found" << endl;
    else
        cout << key << " found" << endl;
    return 0;
}


C




// C function to search a given key in a given BST
 
#include <stdio.h>
#include <stdlib.h>
 
struct node {
    int key;
    struct node *left, *right;
};
 
// A utility function to create a new BST node
struct node* newNode(int item)
{
    struct node* temp
        = (struct node*)malloc(sizeof(struct node));
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}
 
// A utility function to insert
// a new node with given key in BST
struct node* insert(struct node* node, int key)
{
    // If the tree is empty, return a new node
    if (node == NULL)
        return newNode(key);
 
    // Otherwise, recur down the tree
    if (key < node->key)
        node->left = insert(node->left, key);
    else if (key > node->key)
        node->right = insert(node->right, key);
 
    // Return the (unchanged) node pointer
    return node;
}
 
// Utility function to search a key in a BST
struct node* search(struct node* root, int key)
{
    // Base Cases: root is null or key is present at root
    if (root == NULL || root->key == key)
        return root;
 
    // Key is greater than root's key
    if (root->key < key)
        return search(root->right, key);
 
    // Key is smaller than root's key
    return search(root->left, key);
}
 
// Driver Code
int main()
{
    struct node* root = NULL;
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Key to be found
    int key = 6;
 
    // Searching in a BST
    if (search(root, key) == NULL)
        printf("%d not found\n", key);
    else
        printf("%d found\n", key);
 
    key = 60;
 
    // Searching in a BST
    if (search(root, key) == NULL)
        printf("%d not found\n", key);
    else
        printf("%d found\n", key);
    return 0;
}


Java




// Java program to search a given key in a given BST
 
class Node {
    int key;
    Node left, right;
 
    public Node(int item) {
        key = item;
        left = right = null;
    }
}
 
class BinarySearchTree {
    Node root;
 
    // Constructor
    BinarySearchTree() {
        root = null;
    }
 
    // A utility function to insert
    // a new node with given key in BST
    Node insert(Node node, int key) {
        // If the tree is empty, return a new node
        if (node == null) {
            node = new Node(key);
            return node;
        }
 
        // Otherwise, recur down the tree
        if (key < node.key)
            node.left = insert(node.left, key);
        else if (key > node.key)
            node.right = insert(node.right, key);
 
        // Return the (unchanged) node pointer
        return node;
    }
 
    // Utility function to search a key in a BST
    Node search(Node root, int key) {
        // Base Cases: root is null or key is present at root
        if (root == null || root.key == key)
            return root;
 
        // Key is greater than root's key
        if (root.key < key)
            return search(root.right, key);
 
        // Key is smaller than root's key
        return search(root.left, key);
    }
 
    // Driver Code
    public static void main(String[] args) {
        BinarySearchTree tree = new BinarySearchTree();
 
        // Inserting nodes
        tree.root = tree.insert(tree.root, 50);
        tree.insert(tree.root, 30);
        tree.insert(tree.root, 20);
        tree.insert(tree.root, 40);
        tree.insert(tree.root, 70);
        tree.insert(tree.root, 60);
        tree.insert(tree.root, 80);
 
        // Key to be found
        int key = 6;
 
        // Searching in a BST
        if (tree.search(tree.root, key) == null)
            System.out.println(key + " not found");
        else
            System.out.println(key + " found");
 
        key = 60;
 
        // Searching in a BST
        if (tree.search(tree.root, key) == null)
            System.out.println(key + " not found");
        else
            System.out.println(key + " found");
    }
}


Python3




# Python3 function to search a given key in a given BST
 
class Node:
    # Constructor to create a new node
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
 
# A utility function to insert
# a new node with the given key in BST
def insert(node, key):
    # If the tree is empty, return a new node
    if node is None:
        return Node(key)
 
    # Otherwise, recur down the tree
    if key < node.key:
        node.left = insert(node.left, key)
    elif key > node.key:
        node.right = insert(node.right, key)
 
    # Return the (unchanged) node pointer
    return node
 
# Utility function to search a key in a BST
def search(root, key):
    # Base Cases: root is null or key is present at root
    if root is None or root.key == key:
        return root
 
    # Key is greater than root's key
    if root.key < key:
        return search(root.right, key)
 
    # Key is smaller than root's key
    return search(root.left, key)
 
# Driver Code
if __name__ == '__main__':
    root = None
    root = insert(root, 50)
    insert(root, 30)
    insert(root, 20)
    insert(root, 40)
    insert(root, 70)
    insert(root, 60)
    insert(root, 80)
 
    # Key to be found
    key = 6
 
    # Searching in a BST
    if search(root, key) is None:
        print(key, "not found")
    else:
        print(key, "found")
 
    key = 60
 
    # Searching in a BST
    if search(root, key) is None:
        print(key, "not found")
    else:
        print(key, "found")


C#




// C# function to search a given key in a given BST
 
using System;
 
public class Node {
    public int key;
    public Node left, right;
}
 
public class BinaryTree {
    // A utility function to create a new BST node
    public Node NewNode(int item)
    {
        Node temp = new Node();
        temp.key = item;
        temp.left = temp.right = null;
        return temp;
    }
 
    // A utility function to insert
    // a new node with given key in BST
    public Node Insert(Node node, int key)
    {
        // If the tree is empty, return a new node
        if (node == null)
            return NewNode(key);
 
        // Otherwise, recur down the tree
        if (key < node.key)
            node.left = Insert(node.left, key);
        else if (key > node.key)
            node.right = Insert(node.right, key);
 
        // Return the (unchanged) node pointer
        return node;
    }
 
    // Utility function to search a key in a BST
    public Node Search(Node root, int key)
    {
        // Base Cases: root is null or key is present at root
        if (root == null || root.key == key)
            return root;
 
        // Key is greater than root's key
        if (root.key < key)
            return Search(root.right, key);
 
        // Key is smaller than root's key
        return Search(root.left, key);
    }
 
    // Driver Code
    public static void Main()
    {
        Node root = null;
        BinaryTree bt = new BinaryTree();
        root = bt.Insert(root, 50);
        bt.Insert(root, 30);
        bt.Insert(root, 20);
        bt.Insert(root, 40);
        bt.Insert(root, 70);
        bt.Insert(root, 60);
        bt.Insert(root, 80);
 
        // Key to be found
        int key = 6;
 
        // Searching in a BST
        if (bt.Search(root, key) == null)
            Console.WriteLine(key + " not found");
        else
            Console.WriteLine(key + " found");
 
        key = 60;
 
        // Searching in a BST
        if (bt.Search(root, key) == null)
            Console.WriteLine(key + " not found");
        else
            Console.WriteLine(key + " found");
    }
}


Javascript




// Javascript function to search a given key in a given BST
 
class Node {
  constructor(key) {
    this.key = key;
    this.left = null;
    this.right = null;
  }
}
 
// A utility function to insert
// a new node with given key in BST
function insert(node, key) {
  // If the tree is empty, return a new node
  if (node === null) {
    return new Node(key);
  }
 
  // Otherwise, recur down the tree
  if (key < node.key) {
    node.left = insert(node.left, key);
  } else if (key > node.key) {
    node.right = insert(node.right, key);
  }
 
  // Return the (unchanged) node pointer
  return node;
}
 
// Utility function to search a key in a BST
function search(root, key) {
  // Base Cases: root is null or key is present at root
  if (root === null || root.key === key) {
    return root;
  }
 
  // Key is greater than root's key
  if (root.key < key) {
    return search(root.right, key);
  }
 
  // Key is smaller than root's key
  return search(root.left, key);
}
 
// Driver Code
let root = null;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
 
// Key to be found
let key = 6;
 
// Searching in a BST
if (search(root, key) === null) {
  console.log(key + " not found");
} else {
  console.log(key + " found");
}
 
key = 60;
 
// Searching in a BST
if (search(root, key) === null) {
  console.log(key + " not found");
} else {
  console.log(key + " found");
}


Output

6 not found
60 found

Time complexity: O(h), where h is the height of the BST.
Auxiliary Space: O(h), where h is the height of the BST. This is because the maximum amount of space needed to store the recursion stack would be h.

Related Links: 



Previous Article
Next Article

Similar Reads

Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
Given a binary tree, the task is to print the maximum sum of nodes of a sub-tree which is also a Binary Search Tree.Examples: Input : 7 / \ 12 2 / \ \ 11 13 5 / / \ 2 1 38 Output:44 BST rooted under node 5 has the maximum sum 5 / \ 1 38 Input: 5 / \ 9 2 / \ 6 3 / \ 8 7 Output: 8 Here each leaf node represents a binary search tree also a BST with su
12 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Iterative searching in Binary Search Tree
Given a binary search tree and a key. Check the given key exists in BST or not without recursion. Please refer binary search tree insertion for recursive search. C/C++ Code // C++ program to demonstrate searching operation // in binary search tree without recursion #include &lt;bits/stdc++.h&gt; using namespace std; struct Node { int data; struct N
7 min read
Floor in Binary Search Tree (BST)
Given a Binary Search Tree and a number x, find the floor of x in the given BST: Examples: Input: x = 14 and root of below tree 10 / \ 5 15 / \ 12 30 Output: 12 Input: x = 15 and root of below tree 10 / \ 5 15 / \ 12 30 Output: 15 Naive Approach: To solve the problem follow the below idea: A simple solution is to traverse the tree using (Inorder or
7 min read
Insertion in Binary Search Tree (BST)
Given a BST, the task is to insert a new node in this BST. Example: [caption width="800"]Insertion in Binary Search Tree[/caption]How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a le
14 min read
Median of all nodes from a given range in a Binary Search Tree ( BST )
Given a Binary Search Tree (BST)consisting of N nodes and two nodes A and B, the task is to find the median of all the nodes in the given BST whose values lie over the range [A, B]. Examples: Input: A = 3, B = 11 Output: 6Explanation:The nodes that lie over the range [3, 11] are {3, 4, 6, 8, 11}. The median of the given nodes is 6. Input: A = 6, B
10 min read
Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree. Input: [caption width="800"]A Binary Search Tree[/caption] Output: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 100 Input: [caption
11 min read
Implement Binary Search Tree(BST) Iterator
Binary Search Trees (BSTs) are data structures, in computer science. They are commonly used for searching, insertion and deletion operations. In situations it becomes necessary to traverse a BST in an order. For example an in order traversal visits nodes in ascending order based on their values. This article explores the creation of a BSTIterator c
6 min read
Count permutations of given array that generates the same Binary Search Tree (BST)
Given an array, arr[] of size N consisting of elements from the range [1, N], that represents the order, in which the elements are inserted into a Binary Search Tree, the task is to count the number of ways to rearrange the given array to get the same BST. Examples: Input: arr[ ] ={3, 4, 5, 1, 2}Output: 6Explanation :The permutations of the array w
10 min read
Deletion in Binary Search Tree (BST)
Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios: Case 1. Delete a Leaf Node in BST[caption width="800"]Deletion in BST[/caption] Case 2. Delete a Node with Single Child in BSTDeleting a single child node is also simple in BST. Copy the child to the node and delete the node.  [caption width="800"]Dele
15 min read