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 Tutorial
  • Data Structures
  • Algorithms
  • Array
  • Strings
  • Linked List
  • Stack
  • Queue
  • Tree
  • Graph
  • Searching
  • Sorting
  • Recursion
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Divide & Conquer
  • Mathematical
  • Geometric
  • Bitwise
  • Greedy
  • Backtracking
  • Branch and Bound
  • Matrix
  • Pattern Searching
  • Randomized
Open In App
Next Article:
Searching in Binary Search Tree (BST)
Next article icon

Insertion in Binary Search Tree (BST)

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

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

Example:

Insertion-in-BST

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 found, the new node is added as a child of the leaf node. The below steps are followed while we try to insert a node into a binary search tree:

  • Initilize the current node (say, currNode or node) with root node
  • Compare the key with the current node.
  • Move left if the key is less than or equal to the current node value.
  • Move right if the key is greater than current node value.
  • Repeat steps 2 and 3 until you reach a leaf node.
  • Attach the new key as a left or right child based on the comparison with the leaf node’s value.

Follow the below illustration for a better understanding:

Insertion in Binary Search Tree using Recursion:

Below is the implementation of the insertion operation using recursion.

C++14
#include <iostream> using namespace std;  struct Node {     int key;     Node* left;     Node* right;         Node(int item) {         key = item;         left = NULL;         right = NULL;     } };  // A utility function to insert a new node with  // the given key Node* insert(Node* node, int key) {        // If the tree is empty, return a new node     if (node == NULL)          return new Node(key);              // If the key is already present in the tree,     // return the node     if (node->key == key)          return node;          // Otherwise, recur down the tree/ If the key     // to be inserted is greater than the node's key,     // insert it in the right subtree     if (node->key < key)          node->right = insert(node->right, key);          // If the key to be inserted is smaller than      // the node's key,insert it in the left subtree     else          node->left = insert(node->left, key);          // Return the (unchanged) node pointer     return node; }  // A utility function to do inorder tree traversal void inorder(Node* root) {     if (root != NULL) {         inorder(root->left);         cout << root->key << " ";         inorder(root->right);     } }  // Driver program to test the above functions int main() {     // Creating the following BST     //      50     //     /  \     //    30   70     //   / \   / \     //  20 40 60 80      Node* root = new Node(50);     root = insert(root, 30);     root = insert(root, 20);     root = insert(root, 40);     root = insert(root, 70);     root = insert(root, 60);     root = insert(root, 80);      // Print inorder traversal of the BST     inorder(root);      return 0; } 
C
#include <stdio.h> #include <stdlib.h>  // Define the structure for a BST node struct Node {     int key;     struct Node* left;     struct Node* right; };  // 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; }   // Function to insert a new node with the given key struct Node* insert(struct Node* node, int key) {        // If the tree is empty, return a new node     if (node == NULL)         return newNode(key);          // If the key is already present in the tree,     // return the node     if (node->key == key)         return node;          // Otherwise, recur down the tree. If the key      // to be inserted is greater than the node's key,     // insert it in the right subtree     if (node->key < key)         node->right = insert(node->right, key);        // If the key to be inserted is smaller than      // the node's key,insert it in the left subtree     else         node->left = insert(node->left, key);      // Return the (unchanged) node pointer     return node; }  // Function to perform inorder tree traversal void inorder(struct Node* root) {     if (root != NULL) {         inorder(root->left);         printf("%d ", root->key);         inorder(root->right);     } }  // Driver program to test the above functions int main() {     // Creating the following BST     //      50     //     /  \     //    30   70     //   / \   / \     //  20 40 60 80      struct Node* root = newNode(50);     root = insert(root, 30);     root = insert(root, 20);     root = insert(root, 40);     root = insert(root, 70);     root = insert(root, 60);     root = insert(root, 80);      // Print inorder traversal of the BST     inorder(root);      return 0; } 
Java
class Node {     int key;     Node left, right;      public Node(int item)     {         key = item;         left = right = null;     } }  class GfG {      // A utility function to insert a new node     // with the given key     static Node insert(Node root, int key)     {          // If the tree is empty, return a new node         if (root == null)             return new Node(key);          // If the key is already present in the tree,         // return the node         if (root.key == key)             return root;          // Otherwise, recur down the tree         if (key < root.key)             root.left = insert(root.left, key);         else             root.right = insert(root.right, key);          // Return the (unchanged) node pointer         return root;     }      // A utility function to do inorder tree traversal     static void inorder(Node root)     {         if (root != null) {             inorder(root.left);             System.out.print(root.key + " ");             inorder(root.right);         }     }      // Driver method     public static void main(String[] args)     {         Node root = null;          // Creating the following BST         //      50         //     /  \         //    30   70         //   / \   / \         //  20 40 60 80          root = insert(root, 50);         root = insert(root, 30);         root = insert(root, 20);         root = insert(root, 40);         root = insert(root, 70);         root = insert(root, 60);         root = insert(root, 80);          // Print inorder traversal of the BST         inorder(root);     } } 
Python
# Python program to demonstrate # insert operation in binary search tree class Node:     def __init__(self, key):         self.left = None         self.right = None         self.val = key   # A utility function to insert # a new node with the given key def insert(root, key):     if root is None:         return Node(key)     if root.val == key:             return root     if root.val < key:             root.right = insert(root.right, key)     else:             root.left = insert(root.left, key)     return root   # A utility function to do inorder tree traversal def inorder(root):     if root:         inorder(root.left)         print(root.val, end=" ")         inorder(root.right)   # Creating the following BST #      50 #     /  \ #    30   70 #   / \   / \ #  20 40 60 80 r = Node(50) r = insert(r, 30) r = insert(r, 20) r = insert(r, 40) r = insert(r, 70) r = insert(r, 60) r = insert(r, 80)  # Print inorder traversal of the BST inorder(r) 
C#
using System;  class Node {     public int key;     public Node left, right;      public Node(int item) {         key = item;         left = right = null;     } }  class GfG {        // A function to insert a new node with the given key     public static Node Insert(Node node, int key) {         if (node == null)             return new Node(key);                // Duplicates not allowed         if (key == node.key)             return node;                if (key < node.key)             node.left = Insert(node.left, key);         else if (key > node.key)             node.right = Insert(node.right, key);          return node;     }      // A utility function to do inorder tree traversal     public static void Inorder(Node root) {         if (root != null) {             Inorder(root.left);             Console.Write(root.key + " ");             Inorder(root.right);         }     }      // Driver method     public static void Main() {         // Creating the following BST         //      50         //     /  \         //    30   70         //   / \   / \         //  20 40 60 80          Node root = new Node(50);         root = Insert(root, 30);         root = Insert(root, 20);         root = Insert(root, 40);         root = Insert(root, 70);         root = Insert(root, 60);         root = Insert(root, 80);          // Print inorder traversal of the BST         Inorder(root);     } } 
JavaScript
class Node {     constructor(key) {         this.key = key;         this.left = null;         this.right = null;     } }  // A utility function to insert a new // node with the given key function insert(root, key) {      if (root === null)         return new Node(key);              // Duplicates not allowed         if (root.key === key)         return root;              if (key < root.key)         root.left = insert(root.left, key);     else if (key > root.key)         root.right = insert(root.right, key);      return root; }  // A utility function to do inorder // tree traversal function inorder(root) {     if (root !== null) {         inorder(root.left);         console.log(root.key + " ");         inorder(root.right);     } }  // Creating the following BST //      50 //     /  \ //    30   70 //   / \   / \ //  20 40 60 80  let root = new Node(50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80);  // Print inorder traversal of the BST inorder(root); 

Output
20 30 40 50 60 70 80 

Time Complexity: 

  • The worst-case time complexity of insert operations is O(h) where h is the height of the Binary Search Tree. 
  • In the worst case, we may have to travel from the root to the deepest leaf node. The height of a skewed tree may become n and the time complexity of insertion operation may become O(n). 

Auxiliary Space: The auxiliary space complexity of insertion into a binary search tree is O(1)

Insertion in Binary Search Tree using Iterative approach:

Instead of using recursion, we can also implement the insertion operation iteratively using a while loop. Below is the implementation using a while loop.

C++
#include <iostream> using namespace std;  struct Node {     int key;     Node* left;     Node* right;     Node(int item)     {         key = item;         left = NULL;         right = NULL;     } };  Node* insert(Node* root, int x) {      Node* temp = new Node(x);      // If tree is empty     if (root == NULL)         return temp;      // Find the node who is going     // to have the new node temp as     // it child. The parent node is     // mainly going to be a leaf node     Node *parent = NULL, *curr = root;     while (curr != NULL) {         parent = curr;         if (curr->key > x)             curr = curr->left;         else if (curr->key < x)             curr = curr->right;         else             return root;     }      // If x is smaller, make it     // left child, else right child     if (parent->key > x)         parent->left = temp;     else         parent->right = temp;     return root; }  // A utility function to do inorder // tree traversal void inorder(Node* root) {     if (root != NULL) {         inorder(root->left);         cout << root->key << " ";         inorder(root->right);     } }  // Driver program int main() {     // Creating the following BST     //      50     //     /  \     //    30   70     //   / \   / \     //  20 40 60 80      Node* root = new Node(50);     root = insert(root, 30);     root = insert(root, 20);     root = insert(root, 40);     root = insert(root, 70);     root = insert(root, 60);     root = insert(root, 80);      // Print inorder traversal of the BST     inorder(root);      return 0; } 
C
#include <stdio.h> #include <stdlib.h>  // Define the structure for a BST node struct Node {     int key;     struct Node* left;     struct Node* right; };  // 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; }   struct Node* insert(struct Node* root, int x) {      struct Node* temp = newNode(x);      // If tree is empty     if (root == NULL)         return temp;      // Find the node who is going     // to have the new node temp as     // it child. The parent node is     // mainly going to be a leaf node     struct Node *parent = NULL, *curr = root;     while (curr != NULL) {         parent = curr;         if (curr->key > x)             curr = curr->left;         else if (curr->key < x)             curr = curr->right;         else             return root;     }      // If x is smaller, make it     // left child, else right child     if (parent->key > x)         parent->left = temp;     else         parent->right = temp;     return root; }  // Function to perform inorder tree traversal void inorder(struct Node* root) {     if (root != NULL) {         inorder(root->left);         printf("%d ", root->key);         inorder(root->right);     } }  // Driver program to test the above functions int main() {     // Creating the following BST     //      50     //     /  \     //    30   70     //   / \   / \     //  20 40 60 80      struct Node* root = newNode(50);     root = insert(root, 30);     root = insert(root, 20);     root = insert(root, 40);     root = insert(root, 70);     root = insert(root, 60);     root = insert(root, 80);      // Print inorder traversal of the BST     inorder(root);      return 0; } 
Java
class Node {     int key;     Node left, right;     public Node(int item)     {         key = item;         left = right = null;     } }  class GfG {      // Function to insert a new node with     // the given key     static Node insert(Node root, int x) {         Node temp = new Node(x);          // If tree is empty         if (root == null) {             return temp;         }          // Find the node who is going to have          // the new node temp as its child         Node parent = null;         Node curr = root;         while (curr != null) {             parent = curr;             if (curr.key > x) {                 curr = curr.left;             } else if (curr.key < x) {                 curr = curr.right;             } else {                 return root; // Key already exists             }         }          // If x is smaller, make it left          // child, else right child         if (parent.key > x) {             parent.left = temp;         } else {             parent.right = temp;         }         return root;     }      // A utility function to do inorder tree traversal     static void inorder(Node root)     {         if (root != null) {             inorder(root.left);             System.out.print(root.key + " ");             inorder(root.right);         }     }      // Driver method     public static void main(String[] args)     {         Node root = null;          // Creating the following BST         //      50         //     /  \         //    30   70         //   / \   / \         //  20 40 60 80          root = insert(root, 50);         root = insert(root, 30);         root = insert(root, 20);         root = insert(root, 40);         root = insert(root, 70);         root = insert(root, 60);         root = insert(root, 80);          // Print inorder traversal of the BST         inorder(root);     } } 
Python
# Python program to demonstrate # insert operation in binary search tree class Node:     def __init__(self, key):         self.left = None         self.right = None         self.key = key  def insert(root, key):     temp = Node(key)      # If tree is empty     if root is None:         return temp      # Find the node who is going to      # have the new node temp as its child     parent = None     curr = root     while curr is not None:         parent = curr         if curr.key > key:             curr = curr.left         elif curr.key < key:             curr = curr.right         else:             return root  # Key already exists      # If key is smaller, make it left      # child, else right child     if parent.key > key:         parent.left = temp     else:         parent.right = temp      return root   # A utility function to do inorder tree traversal def inorder(root):     if root:         inorder(root.left)         print(root.key, end=" ")         inorder(root.right)   # Creating the following BST #      50 #     /  \ #    30   70 #   / \   / \ #  20 40 60 80 r = Node(50) r = insert(r, 30) r = insert(r, 20) r = insert(r, 40) r = insert(r, 70) r = insert(r, 60) r = insert(r, 80)  # Print inorder traversal of the BST inorder(r) 
C#
using System;  class Node {     public int key;     public Node left, right;      public Node(int item) {         key = item;         left = right = null;     } }  class GfG {        // Function to insert a new node with the given key     public static Node Insert(Node root, int x)     {         Node temp = new Node(x);          // If tree is empty         if (root == null)             return temp;          // Find the node who is going to          // have the new node temp as its child         Node parent = null;         Node curr = root;         while (curr != null)         {             parent = curr;             if (curr.key > x)                 curr = curr.left;             else if (curr.key < x)                 curr = curr.right;             else                 return root; // Key already exists         }          // If x is smaller, make it left          // child, else right child         if (parent.key > x)             parent.left = temp;         else             parent.right = temp;          return root;     }        // A utility function to do inorder tree traversal     public static void Inorder(Node root) {         if (root != null) {             Inorder(root.left);             Console.Write(root.key + " ");             Inorder(root.right);         }     }      // Driver method     public static void Main() {         // Creating the following BST         //      50         //     /  \         //    30   70         //   / \   / \         //  20 40 60 80          Node root = new Node(50);         root = Insert(root, 30);         root = Insert(root, 20);         root = Insert(root, 40);         root = Insert(root, 70);         root = Insert(root, 60);         root = Insert(root, 80);          // Print inorder traversal of the BST         Inorder(root);     } } 
JavaScript
class Node {     constructor(key)     {         this.key = key;         this.left = null;         this.right = null;     } }  // Function to insert a new node with the given key function insert(root, x) {     const temp = new Node(x);      // If tree is empty     if (root === null)         return temp;      // Find the node who is going to have     // the new node temp as its child     let parent = null;     let curr = root;     while (curr !== null) {         parent = curr;         if (curr.key > x)             curr = curr.left;         else if (curr.key < x)             curr = curr.right;         else             return root; // Key already exists     }      // If x is smaller, make it left     // child, else right child     if (parent.key > x)         parent.left = temp;     else         parent.right = temp;      return root; }  // A utility function to do inorder tree traversal function inorder(root) {     if (root !== null) {         inorder(root.left);         console.log(root.key + " ");         inorder(root.right);     } }  // Creating the following BST //      50 //     /  \ //    30   70 //   / \   / \ //  20 40 60 80  let root = new Node(50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80);  // Print inorder traversal of the BST inorder(root); 

Output
20 30 40 50 60 70 80 

The time complexity of inorder traversal is O(n), as each node is visited once. 
The Auxiliary space is O(n), as we use a stack to store nodes for recursion.

Related Links: 

  • Binary Search Tree Search Operation
  • Binary Search Tree Delete Operation


Next Article
Searching in Binary Search Tree (BST)

I

itsadityash
Improve
Article Tags :
  • DSA

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