Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice on BST
  • MCQs on BST
  • BST Tutorial
  • BST Insertion
  • BST Traversals
  • BST Searching
  • BST Deletion
  • Check BST
  • Balance a BST
  • Self-Balancing BST
  • AVL Tree
  • Red-Black Tree
  • Splay Tree
  • BST Application
  • BST Advantage
Open In App
Next Article:
Deletion in Binary Search Tree (BST)
Next article icon

Searching in Binary Search Tree (BST)

Last Updated : 25 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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.  

Input: Root of the below BST

Searching-Example-1

Output: True
Explanation: 8 is present in the BST as right child of root

Input: Root of the below BST

Searching-Example-2

Output: False
Explanation: 14 is not present in the BST

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:


Recursive Program to implement search in BST:

C++
#include <iostream> using namespace std;  struct Node {     int key;     Node* left;     Node* right;     Node(int item) {         key = item;         left = right = NULL;     } };  // 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 int main() {        // Creating a hard coded tree for keeping      // the length of the code small. We need      // to make sure that BST properties are      // maintained if we try some other cases.     Node* root = new Node(50);     root->left = new Node(30);     root->right = new Node(70);     root->left->left = new Node(20);     root->left->right = new Node(40);     root->right->left = new Node(60);     root->right->right = new Node(80);        (search(root, 19) != NULL)? cout << "Found\n":                                 cout << "Not Found\n";         (search(root, 80) != NULL)? cout << "Found\n":                                 cout << "Not Found\n";      return 0; } 
C
#include <stdio.h> #include <stdlib.h>  struct Node {     int key;     struct Node* left;     struct Node* right; };  // Constructor 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; }  // 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() {     // Creating a hard coded tree for keeping      // the length of the code small. We need      // to make sure that BST properties are      // maintained if we try some other cases.     struct Node* root = newNode(50);     root->left = newNode(30);     root->right = newNode(70);     root->left->left = newNode(20);     root->left->right = newNode(40);     root->right->left = newNode(60);     root->right->right = newNode(80);      printf(search(root, 19) != NULL ? "Found\n"                                     : "Not Found\n");     printf(search(root, 80) != NULL ? "Found\n"                                     : "Not Found\n");      return 0; } 
Java
class Node {     int key;     Node left, right;      public Node(int item)     {         key = item;         left = right = null;     } } class GfG {      // function to search a key in a BST     static 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);     }      public static void main(String[] args)     {                  // Creating a hard coded tree for keeping          // the length of the code small. We need          // to make sure that BST properties are          // maintained if we try some other cases.         Node root = new Node(50);         root.left = new Node(30);         root.right = new Node(70);         root.left.left = new Node(20);         root.left.right = new Node(40);         root.right.left = new Node(60);         root.right.right = new Node(80);          // Searching for keys in the BST         System.out.println(search(root, 19) != null                                ? "Found"                                : "Not Found");         System.out.println(search(root, 80) != null                                ? "Found"                                : "Not Found");     } } 
Python
class Node:     def __init__(self, key):         self.key = key         self.left = None         self.right = None  # 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)    # Creating a hard coded tree for keeping   # the length of the code small. We need   # to make sure that BST properties are   # maintained if we try some other cases. root = Node(50) root.left = Node(30) root.right = Node(70) root.left.left = Node(20) root.left.right = Node(40) root.right.left = Node(60) root.right.right = Node(80)  # Searching for keys in the BST print("Found" if search(root, 19) else "Not Found") print("Found" if search(root, 80) else "Not Found") 
C#
using System;  public class Node {     public int Key;     public Node Left, Right;      public Node(int item)     {         Key = item;         Left = Right = null;     } }  public class GfG {     // function to search a key in a BST     public static 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()     {          // Creating a hard coded tree for keeping          // the length of the code small. We need          // to make sure that BST properties are          // maintained if we try some other cases.         Node root = new Node(50);         root.Left = new Node(30);         root.Right = new Node(70);         root.Left.Left = new Node(20);         root.Left.Right = new Node(40);         root.Right.Left = new Node(60);         root.Right.Right = new Node(80);          // Searching for keys in the BST         Console.WriteLine(Search(root, 19) != null ? "Found" : "Not Found");         Console.WriteLine(Search(root, 80) != null ? "Found" : "Not Found");     } } 
JavaScript
class Node {     constructor(key)     {         this.key = key;         this.left = null;         this.right = null;     } }  // 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); }   // Creating a hard coded tree for keeping  // the length of the code small. We need  // to make sure that BST properties are  // maintained if we try some other cases. let root = new Node(50); root.left = new Node(30); root.right = new Node(70); root.left.left = new Node(20); root.left.right = new Node(40); root.right.left = new Node(60); root.right.right = new Node(80);  // Searching for keys in the BST console.log(search(root, 19) !== null ? "Found"                                       : "Not Found"); console.log(search(root, 80) !== null ? "Found"                                       : "Not Found"); 

Output
Not Found Found 

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

We can avoid the auxiliary space and recursion overhead withe help of iterative implementation. Below is link for the iterative implementation that works in O(h) time and O(1) auxiliary space.

Iterative Program to implement search in BST



Next Article
Deletion in Binary Search Tree (BST)
author
kartik
Improve
Article Tags :
  • Binary Search Tree
  • DSA
  • Amazon
  • Linkedin
  • Microsoft
  • Samsung
Practice Tags :
  • Amazon
  • Linkedin
  • Microsoft
  • Samsung
  • Binary Search Tree

Similar Reads

  • Binary Search Tree
    A Binary Search Tree (or BST) is a data structure used in computer science for organizing and storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right chi
    3 min read
  • Introduction to Binary Search Tree
    Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Binary search tree follows all properties of binary tree and for every nodes, its left subtree contains values less than the node and the right subtree contains values greater than the
    3 min read
  • Applications of BST
    Binary Search Tree (BST) is a data structure that is commonly used to implement efficient searching, insertion, and deletion operations along with maintaining sorted sequence of data. Please remember the following properties of BSTs before moving forward. The left subtree of a node contains only nod
    2 min read
  • Applications, Advantages and Disadvantages of Binary Search Tree
    A Binary Search Tree (BST) is a data structure used to storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the p
    2 min read
  • Insertion in Binary Search Tree (BST)
    Given a BST, the task is to insert a new node in this BST. Example: 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 leaf node is f
    15+ min read
  • Searching in Binary Search Tree (BST)
    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. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInp
    7 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 Case 2. Delete a Node with Single Child in BST Deleting a single child node is also simple in BST. Copy the child to the node and delete the node. Case 3. Delete a Node
    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:  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:  Output:
    11 min read
  • Balance a Binary Search Tree
    Given a BST (Binary Search Tree) that may be unbalanced, the task is to convert it into a balanced BST that has the minimum possible height. Examples: Input: Output: Explanation: The above unbalanced BST is converted to balanced with the minimum possible height. Input: Output: Explanation: The above
    10 min read
  • Self-Balancing Binary Search Trees
    Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keep the height as small as possible when insertion and deletion operations are performed on the tree. The height is typically maintained in order of logN so that all operations take O(logN) time on average
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences