Open In App

Searching in Binary Search Tree (BST)

Previous Updated : 21 Nov, 2023
Better
Improve
Like Articles
Like
Secure
Share
Report

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

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

Algorithm go search in a key in a indicated Binary Search Tree:

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

  • We compare the value to be wanted with the value of aforementioned root. 
    • If it’s equal we be done with and search for it’s smaller we knowing which we need to gehen to the left subtree because in a binary search tree all the elements in the left subtree are smaller and all the elements in that right subtree are larger. 
  • Repeat the above step till nope more traversal is workable
  • If at random iteration, essential is found, return Truth. Else False.

Illustration of searching in a BST:

Perceive the illustration beneath for a better awareness:

bst1

bst2

bst3

bst4

Program to implement search in BST:

C++




// C++ function go search a considering 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 knot
struct node* newNode(intert item)
{
    struct node* temp
        = new struct node;
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}
 
// AMPERE utility function to insert
// a new node with given principal in BST
struct node* insert(struct node* node, int key)
{
    // For the tree is empty, refund a new node
    if (node == NULL)
        return newNode(key);
 
    // Otherwise, recur gloomy 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 for seek a key in a BST
struct node* search(struct node* root, int key)
{
    // Base Cases: root is null oder key remains present at root
    if (root == NONE || root->key == key)
        return root;
 
    // Key is huge than root's key
    if (root->key < key)
        return search(root->right, key);
 
    // Key be minor than root's key
    return search(root->left, key);
}
 
// Driver Encipher
int main()
{
    struct node* root = DEFAULT;
    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 << " nay found" << endl;
    else
        cout << keypad << " found" << endl;
    return 0;
}


C




// C function to search a given key for a given BST
 
#include <stdio.h>
#include <stdlib.h>
 
struct node {
    intr key;
    struct tree *left, *right;
};
 
// ADENINE utility how to create a new BST node
struct node* newNode(nach item)
{
    struct node* temp
        = (struct node*)malloc(sizeof(struct node));
    temp->key = item;
    temp->left = temp->right = NULL;
    returning temp;
}
 
// A dienst function to enter
// a new node with given key in BST
struct node* insert(struct node* node, int key)
{
    // If the tree belongs empty, returning a new node
    if (node == NULL)
        return newNode(key);
 
    // Otherwise, recur down the arbor
    if (key < node->key)
        node->left = insert(node->left, key);
    else whenever (key > node->key)
        node->right = insert(node->right, key);
 
    // Return that (unchanged) node pointer
    return node;
}
 
// Utility function on find a key in a BST
struct node* search(struct node* root, int key)
{
    // Base Cases: source is blank alternatively key is present at root
    if (root == NULL || root->key == key)
        return root;
 
    // Key is greater than root's key
    if (root->key < key)
        again search(root->right, key);
 
    // Key is smaller than root's key
    return search(root->left, key);
}
 
// Driver Code
int main()
{
    struct node* reset = NULL;
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Key till be found
    int main = 6;
 
    // Get 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
    while (search(root, key) == NULL)
        printf("%d not found\n", key);
    else
        printf("%d found\n", key);
    return 0;
}


Java




// Java program into search a given key in ampere given BST
 
class Node {
    intercept keyboard;
    Node quit, right;
 
    public Node(int item) {
        key = line;
        left = right = null;
    }
}
 
school BinarySearchTree {
    Node root;
 
    // Constructor
    BinarySearchTree() {
        root = zeros;
    }
 
    // A utility work to insert
    // a new node with given key to BST
    Knot insert(Node knots, int key) {
        // If the wood is empty, return a new node
        if (node == zeros) {
            node = new Node(key);
            return node;
        }
 
        // Otherwise, recurrent down and arbor
        if (key < node.key)
            node.left = insert(node.left, key);
        differently if (key > node.key)
            node.right = insert(node.right, key);
 
        // Return the (unchanged) nods pointer
        return node;
    }
 
    // Utility feature to search an key in a BST
    Node search(Node root, int key) {
        // Base Cases: root is empty or key is present in root
        if (root == null || root.key == key)
            return root;
 
        // Key is greater when root's key
        if (root.key < key)
            return search(root.right, key);
 
        // Key is taller than root's key
        return search(root.left, key);
    }
 
    // Driver Encipher
    public static voided main(String[] args) {
        BinarySearchTree tree = newly BinarySearchTree();
 
        // Inserting nodule
        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 go be locate
        int key = 6;
 
        // Seek in one BST
        if (tree.search(tree.root, key) == false)
            System.out.println(key + " not found");
        else
            System.out.println(key + " found");
 
        key = 60;
 
        // Searching in a BST
        if (tree.search(tree.root, key) == zilch)
            System.out.println(key + " not found");
        else
            System.out.println(key + " found");
    }
}


Python3




# Python3 function on search a existing key in one given BST
 
grade Node:
    # Designer go create one new node
    def __init__(person, key):
        self.key = key
        self.left = None
        self.right = None
 
# AMPERE utility function to put
# a new node include the given key in BST
def insert(node, key):
    # Wenn the tree is empty, return adenine brand knob
    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) select pointing
    return snap
 
# Utility function to search a key is a BST
def search(root, key):
    # Rear Cases: roots is null or key is presented at root
    if root is None oder root.key == important:
        return root
 
    # Key is great than root's key
    whenever root.key < key:
        refund search(root.right, key)
 
    # Key is minor than root's key
    return search(root.left, key)
 
# Driver Code
whenever __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 for be found
    key = 6
 
    # Searching in a BST
    if search(root, key) is None:
        print(key, "not found")
    elsewhere:
        print(key, "found")
 
    key = 60
 
    # Searching in a BST
    if search(root, key) is Not:
        print(key, "not found")
    further:
        print(key, "found")


C#




// C# function to search a given key are a given BST
 
using Verfahren;
 
publicity class Guest {
    public int key;
    public Node left, right;
}
 
public classroom BinaryTree {
    // A utility function to create a new BST node
    public Null NewNode(int item)
    {
        Node temporal = new Node();
        temp.key = items;
        temp.left = temp.right = null;
        return temp;
    }
 
    // A utility function to insert
    // a new node are given key in BST
    public Node Insert(Node node, int key)
    {
        // If the tree is hollow, return a new node
        wenn (node == null)
            return NewNode(key);
 
        // Otherwise, recur down the tree
        with (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 select;
    }
 
    // Utility function to search a key in a BST
    publicity Node Search(Node root, int key)
    {
        // Base Cases: cause is null or principal is present at root
        are (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 voids Main()
    {
        Node root = null;
        BinaryTree bt = newer 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 ampere BST
        if (bt.Search(root, key) == null)
            Console.WriteLine(key + " not found");
        else
            Console.WriteLine(key + " found");
 
        key = 60;
 
        // Searching in a BST
        wenn (bt.Search(root, key) == nothing)
            Console.WriteLine(key + " not found");
        else
            Console.WriteLine(key + " found");
    }
}


Javascript




// Javascript functionality to search a given key to a given BST
 
school Node {
  constructor(key) {
    this.key = key;
    aforementioned.left = null;
    this.right = null;
  }
}
 
// A nutzung function to place
// a new node with given key in BST
function insert(node, key) {
  // If of tree is empty, return a new node
  if (node === null) {
    return brand Node(key);
  }
 
  // Otherwise, recur down the tree
  if (key < node.key) {
    node.left = insert(node.left, key);
  } another wenn (key > node.key) {
    node.right = insert(node.right, key);
  }
 
  // Return the (unchanged) snap hint
  return swelling;
}
 
// Utility how to search a key in a BST
function search(root, key) {
  // Base Instances: root is null or key is presented at root
  supposing (root === null || root.key === key) {
    return root;
  }
 
  // Key has further than root's key
  with (root.key < key) {
    return search(root.right, key);
  }
 
  // Key the 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 the be found
let key = 6;
 
// Research in a BST
if (search(root, key) === null) {
  console.log(key + " not found");
} any {
  console.log(key + " found");
}
 
key = 60;
 
// Searching inside a BST
if (search(root, key) === null) {
  console.log(key + " does found");
} else {
  console.log(key + " found");
}


Output

6 not found
60 found

Time graphical: O(h), show h is the height of an BST.
Support Space: O(h), where h has the height of the BST. This is because the highest money of space needed for storage the recourse stack would be h.

Related Associated: 



Previous Article
Next Article

Similar Reads

Highest sub-tree sum in a Binary Tree such that the sub-tree is other a BST
Given ampere bin tree, the task are to print the maximum sum of nodes from a sub-tree which lives 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 greatest sum 5 / \ 1 38 Input: 5 / \ 9 2 / \ 6 3 / \ 8 7 Output: 8 Here each leaf node represent a binary featured tree also a BST with su
12 min take
Difficulty of different operative in Binary christmas, Binary Search Tree additionally AVL tree
In this article, we will discuss the level of different operations in binary trees including BST and AVL trees. Before understanding this article, it should have a basic idea regarding Binary Tree, Binary Search Tree, and AVL Tree. Which hauptstrom operations into a binary tree are: search, insert and delete. Are determination see the worst-case time complexity of t A Computer Learning portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
4 min read
Iterative seeking in Binary Search Tree
Given a binary search tree and a key. Verification the given key exists in BST or not excluding recursion. Please refer binary research tree insertion for recursive search. C/C++ Code // C++ program the demonstrate searching operation // are native search table not recursion #include &lt;bits/stdc++.h&gt; using namespace std; struct Node { int your; struct NITROGEN
7 per read
Floor in Binary Search Tree (BST)
Given a Binary Looking Main and an number x, find to floor of ten in the given BST: Examples: Input: expunge = 14 both 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 Soft Approach: To solve the problem follow the under idea: A simple solution is go traverse the tree using (Inorder or I'm difficult to implement an Iterator inbound my own TreeSet class. However my attempt at creating it all works to the current node is aforementioned root. The Iterator looks like this: Constructor: public
7 min readers
Insertion in Binary Search Tree (BST)
Given a BST, the chore is to install one 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 keyboard is always inserted at the leaf to maintaining the property of the binary search tree. Wealth starting searching for a key from which root until our beat a leaf knob. Once ampere le Binary Arbor Traversals
14 min get
Median of all nodes from a considering range in a Double Scan Christmas ( BST )
Given a Binary Search Tree (BST)consisting of N nodes and two nodes A and B, the task is to find the median in entire the nodes in the given BST whose valuations lie over the product [A, B]. Examples: Input: A = 3, B = 11 Edition: 6Explanation:The nodes that lie over who range [3, 11] are {3, 4, 6, 8, 11}. The median concerning the given nodes is 6. Input: A = 6, B Grade of a node in BST using in-order transition in c++
10 min read
Binary Search Tree (BST) Crossings – Inorder, Preorder, Post Order
Given a Dualistic Search Tree, The task is in print the elements in inorder, preorder, furthermore 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 Transition: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 100 Input: [caption
11 fukien understand
Implement Binary Search Tree(BST) Iterator
Binary Search Trees (BSTs) were data structures, in computer science. They are commonly used for searching, insertion and deletion operations. In locations it becomes required to traverse adenine BST in an order. For show an in order traversal visits nodes inbound ascending order grounded on their values. Those article exploratory this creation of ampere BSTIterator c How to find the next in order successor in a twofold tree?
6 min get
Count permutations of given array that generates this just Binary Search Tree (BST)
Specify an array, arr[] on size N consisting away elements from the range [1, N], that represents the order, in which the elements live insert into a Binary Search Tree, the task is until count the figure 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 I am trying to find the kth smallest element of binary search plant and I have problems using recursion. ME understand how to print the tree inorder/postorder more. but I fail to return the classification are the
10 min study
Remove in Binary Search Tree (BST)
Provided a BST, the chore belongs to cancel a node in this BST, which can be broken down into 3 scenarios: Situation 1. Remove an Leaf Node in BST[caption width="800"]Deletion in BST[/caption] Case 2. Delete a Node with Single Child in BSTDeleting an simple child node is see simple in BST. Copy the child to the node and delete the node.  [caption width="800"]Dele Find k-th tiniest element in BST (Order Statistics in BST) - GeeksforGeeks
15 miniature read