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:
Check if a Binary Tree is BST or not
Next article icon

Iterative searching in Binary Search Tree

Last Updated : 30 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Search Tree and a key, the task is to find if the node with a value key is present in the BST or not.

Example:

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

Approach:

The idea is to traverse the Binary search tree, starting from the root node. If the current node’s data is equal to key, then return true. If node’s value is less than key, then traverse the right subtree by updateing current as current’right. Else, set current as current’left to travrese in left subtree. If current becomes NULL , key is not present in the BST, return false.

Below is implementation of the above approach:

C++
// C++ program to search in  // a BST. #include <iostream> using namespace std;  class Node { public:     int data;     Node* left;     Node* right;     Node(int x) {         data = x;         left = nullptr;         right = nullptr;     } };  // Function to search in a bst. bool search(struct Node* root, int x) {          Node* curr = root;          while (curr != nullptr) {                  // If curr node is x         if (curr->data == x)             return true;                      // Search in right subtree         else if (curr->data < x)              curr = curr->right;                      // Search in right subtree         else             curr = curr->left;     }          // If x is not found.     return false; }  int main() {          // Create a hard coded BST.     //        20     //       /  \     //      8   22     //     / \     //   4   12     //       /  \     //     10   14     Node* root = new Node(20);     root->left = new Node(8);     root->left->left = new Node(4);     root->left->right = new Node(12);     root->left->right->left = new Node(10);     root->left->right->right = new Node(14);     root->right = new Node(22);      	int x = 12;          if(search(root, x)) {       cout << "True";     }   	else  cout << "False";     return 0; } 
C
// C program to search in  // a BST. #include <stdio.h> #include <stdlib.h>  struct Node {     int data;     struct Node* left;     struct Node* right; };  // Function to search in a bst. int search(struct Node* root, int x) {          struct Node* curr = root;          while (curr != NULL) {                  // If curr node is x         if (curr->data == x)             return 1;                      // Search in right subtree         else if (curr->data < x)              curr = curr->right;                      // Search in left subtree         else             curr = curr->left;     }          // If x is not found.     return 0; }  struct Node* createNode(int x) {     struct Node* newNode =      	(struct Node*)malloc(sizeof(struct Node));     newNode->data = x;     newNode->left = NULL;     newNode->right = NULL;     return newNode; }  int main() {          // Create a hard coded BST.     //        20     //       /  \     //      8   22     //     / \     //   4   12     //       /  \     //     10   14     struct Node* root = createNode(20);     root->left = createNode(8);     root->left->left = createNode(4);     root->left->right = createNode(12);     root->left->right->left = createNode(10);     root->left->right->right = createNode(14);     root->right = createNode(22);          int x = 12;   	if(search(root, x)) {        printf("True");     }   	else printf("False");        return 0; } 
Java
// Java program to search in  // a BST. class Node {     int data;     Node left, right;      public Node(int x) {         data = x;         left = null;         right = null;     } }  class GfG {          // Function to search in a bst.     static boolean search(Node root, int x) {                  Node curr = root;                  while (curr != null) {                          // If curr node is x             if (curr.data == x)                 return true;                              // Search in right subtree             else if (curr.data < x)                  curr = curr.right;                              // Search in left subtree             else                 curr = curr.left;         }                  // If x is not found.         return false;     }      public static void main(String[] args) {                  // Create a hard coded BST.         //        20         //       /  \         //      8   22         //     / \         //   4   12         //       /  \         //     10   14         Node root = new Node(20);         root.left = new Node(8);         root.left.left = new Node(4);         root.left.right = new Node(12);         root.left.right.left = new Node(10);         root.left.right.right = new Node(14);         root.right = new Node(22);                  int x = 12;         System.out.println(search(root, x));     } } 
Python
# Python program to search in  # a BST. class Node:     def __init__(self, x):         self.data = x         self.left = None         self.right = None  # Function to search in a bst. def search(root, x):          curr = root          while curr is not None:                  # If curr node is x         if curr.data == x:             return True                      # Search in right subtree         elif curr.data < x:             curr = curr.right                      # Search in left subtree         else:             curr = curr.left          # If x is not found.     return False  if __name__ == "__main__":          # Create a hard coded BST.     #        20     #       /  \     #      8   22     #     / \     #   4   12     #       /  \     #     10   14     root = Node(20)     root.left = Node(8)     root.left.left = Node(4)     root.left.right = Node(12)     root.left.right.left = Node(10)     root.left.right.right = Node(14)     root.right = Node(22)          x = 12     print(search(root, x)) 
C#
// C# program to search in  // a BST. 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 search in a bst.     static bool search(Node root, int x) {                  Node curr = root;                  while (curr != null) {                          // If curr node is x             if (curr.data == x)                 return true;                              // Search in right subtree             else if (curr.data < x)                  curr = curr.right;                              // Search in left subtree             else                 curr = curr.left;         }                  // If x is not found.         return false;     }      static void Main(string[] args) {                  // Create a hard coded BST.         //        20         //       /  \         //      8   22         //     / \         //   4   12         //       /  \         //     10   14         Node root = new Node(20);         root.left = new Node(8);         root.left.left = new Node(4);         root.left.right = new Node(12);         root.left.right.left = new Node(10);         root.left.right.right = new Node(14);         root.right = new Node(22);                  int x = 12;         Console.WriteLine(search(root, x));     } } 
JavaScript
// JavaScript program to search in  // a BST. class Node {     constructor(x) {         this.data = x;         this.left = null;         this.right = null;     } }  // Function to search in a bst. function search(root, x) {          let curr = root;          while (curr !== null) {                  // If curr node is x         if (curr.data === x)             return true;                      // Search in right subtree         else if (curr.data < x)              curr = curr.right;                      // Search in left subtree         else             curr = curr.left;     }          // If x is not found.     return false; }  // Create a hard coded BST. //        20 //       /  \ //      8   22 //     / \ //   4   12 //       /  \ //     10   14 let root = new Node(20); root.left = new Node(8); root.left.left = new Node(4); root.left.right = new Node(12); root.left.right.left = new Node(10); root.left.right.right = new Node(14); root.right = new Node(22);  let x = 12; console.log(search(root, x)); 

Output
True

Time Complexity: O(h), where h is the height of the BST.
Auxiliary Space: O(1)

Related article:

  • Searching in Binary Search Tree (BST)


Next Article
Check if a Binary Tree is BST or not

S

Shahnawaz_Ali
Improve
Article Tags :
  • Binary Search Tree
  • DSA
Practice Tags :
  • 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