Given a BST, the task is to insert a new node in this BST.
Example:
Insertion in Binary Search Tree
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:
- Check the value to be inserted (say X) with the value of the current node (say val) we are in:
- If X is less than val move to the left subtree.
- Otherwise, move to the right subtree.
- Once the leaf node is reached, insert X to its right or left based on the relation between X and the leaf node’s value.
Follow the below illustration for a better understanding:
Illustration:
![]()
Insertion in BST
![]()
Insertion in BST
![]()
Insertion in BST
![]()
Insertion in BST
![]()
Insertion in BST
Insertion in Binary Search Tree using Recursion:
Below is the implementation of the insertion operation using recursion.
C++14
// C++ program to demonstrate insertion// in a BST recursivelyÂ
#include <bits/stdc++.h>using namespace std;Â
class BST {Â Â Â Â int data;Â Â Â Â BST *left, *right;Â
public:    // Default constructor.    BST();Â
    // Parameterized constructor.    BST(int);Â
    // Insert function.    BST* Insert(BST*, int);Â
    // Inorder traversal.    void Inorder(BST*);};Â
// Default Constructor definition.BST::BST()Â Â Â Â : data(0)Â Â Â Â , left(NULL)Â Â Â Â , right(NULL){}Â
// Parameterized Constructor definition.BST::BST(int value){Â Â Â Â data = value;Â Â Â Â left = right = NULL;}Â
// Insert function definition.BST* BST::Insert(BST* root, int value){Â Â Â Â if (!root) {Â
        // Insert the first node, if root is NULL.        return new BST(value);    }Â
    // Insert data.    if (value > root->data) {        // Insert right node data, if the 'value'        // to be inserted is greater than 'root' node data.Â
        // Process right nodes.        root->right = Insert(root->right, value);    }    else if (value < root->data) {        // Insert left node data, if the 'value'        // to be inserted is smaller than 'root' node data.Â
        // Process left nodes.        root->left = Insert(root->left, value);    }Â
    // Return 'root' node, after insertion.    return root;}Â
// Inorder traversal function.// This gives data in sorted order.void BST::Inorder(BST* root){Â Â Â Â if (!root) {Â Â Â Â Â Â Â Â return;Â Â Â Â }Â Â Â Â Inorder(root->left);Â Â Â Â cout << root->data << " ";Â Â Â Â Inorder(root->right);}Â
// Driver codeint main(){Â Â Â Â BST b, *root = NULL;Â Â Â Â root = b.Insert(root, 50);Â Â Â Â b.Insert(root, 30);Â Â Â Â b.Insert(root, 20);Â Â Â Â b.Insert(root, 40);Â Â Â Â b.Insert(root, 70);Â Â Â Â b.Insert(root, 60);Â Â Â Â b.Insert(root, 80);Â
    b.Inorder(root);    return 0;} |
C
// C program to demonstrate insert// operation in binary// search tree.Â
#include <stdio.h>#include <stdlib.h>Â
struct node {Â Â Â Â int key;Â Â Â Â struct node *left, *right;};Â
// A utility function to create a new BST nodestruct 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 do inorder traversal of BSTvoid inorder(struct node* root){Â Â Â Â if (root != NULL) {Â Â Â Â Â Â Â Â inorder(root->left);Â Â Â Â Â Â Â Â printf("%d ", root->key);Â Â Â Â Â Â Â Â inorder(root->right);Â Â Â Â }}Â
// A utility function to insert// a new node with given key in BSTstruct 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;}Â
// Driver Codeint main(){Â Â Â Â /* Let us create following BSTÂ Â Â Â Â Â Â Â Â Â Â Â Â Â 50Â Â Â Â Â Â Â Â Â Â Â /Â Â Â Â \Â Â Â Â Â Â Â Â Â Â 30Â Â Â Â Â 70Â Â Â Â Â Â Â Â Â /Â \Â Â Â /Â \Â Â Â Â Â Â Â 20Â Â 40Â 60Â Â 80 */Â Â Â Â 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);Â
    // Print inorder traversal of the BST    inorder(root);Â
    return 0;} |
Java
// Java program to demonstrate// insert operation in binary// search treeÂ
import java.io.*;Â
public class BinarySearchTree {Â
    // Class containing left    // and right child of current node    // and key value    class Node {        int key;        Node left, right;Â
        public Node(int item)        {            key = item;            left = right = null;        }    }Â
    // Root of BST    Node root;Â
    // Constructor    BinarySearchTree() { root = null; }Â
    BinarySearchTree(int value) { root = new Node(value); }Â
    // This method mainly calls insertRec()    void insert(int key) { root = insertRec(root, key); }Â
    // A recursive function to    // insert a new key in BST    Node insertRec(Node root, int key)    {        // If the tree is empty,        // return a new node        if (root == null) {            root = new Node(key);            return root;        }Â
        // Otherwise, recur down the tree        else if (key < root.key)            root.left = insertRec(root.left, key);        else if (key > root.key)            root.right = insertRec(root.right, key);Â
        // Return the (unchanged) node pointer        return root;    }Â
    // This method mainly calls InorderRec()    void inorder() { inorderRec(root); }Â
    // A utility function to    // do inorder traversal of BST    void inorderRec(Node root)    {        if (root != null) {            inorderRec(root.left);            System.out.print(root.key + " ");            inorderRec(root.right);        }    }Â
    // Driver Code    public static void main(String[] args)    {        BinarySearchTree tree = new BinarySearchTree();Â
        /* Let us create following BST              50           /    \          30     70         / \   / \       20  40 60  80 */        tree.insert(50);        tree.insert(30);        tree.insert(20);        tree.insert(40);        tree.insert(70);        tree.insert(60);        tree.insert(80);Â
        // Print inorder traversal of the BST        tree.inorder();    }}Â
// This code is contributed by Ankur Narain Verma |
Python3
# Python program to demonstrate# insert operation in binary search treeÂ
Â
# A utility class that represents# an individual node in a BSTclass 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 keydef insert(root, key):    if root is None:        return Node(key)    else:        if root.val == key:            return root        elif 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 traversaldef inorder(root):Â Â Â Â if root:Â Â Â Â Â Â Â Â inorder(root.left)Â Â Â Â Â Â Â Â print(root.val, end=" ")Â Â Â Â Â Â Â Â inorder(root.right)Â
Â
# Driver program to test the above functionsif __name__ == '__main__':Â
    # Let us create 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#
// C# program to demonstrate// insert operation in binary// search treeÂ
using System;Â
class BinarySearchTree {Â
    // Class containing left and    // right child of current node    // and key value    public class Node {        public int key;        public Node left, right;Â
        public Node(int item)        {            key = item;            left = right = null;        }    }Â
    // Root of BST    Node root;Â
    // Constructor    BinarySearchTree() { root = null; }Â
    BinarySearchTree(int value) { root = new Node(value); }Â
    // This method mainly calls insertRec()    void insert(int key) { root = insertRec(root, key); }Â
    // A recursive function to insert    // a new key in BST    Node insertRec(Node root, int key)    {Â
        // If the tree is empty,        // return a new node        if (root == null) {            root = new Node(key);            return root;        }Â
        // Otherwise, recur down the tree        if (key < root.key)            root.left = insertRec(root.left, key);        else if (key > root.key)            root.right = insertRec(root.right, key);Â
        // Return the (unchanged) node pointer        return root;    }Â
    // This method mainly calls InorderRec()    void inorder() { inorderRec(root); }Â
    // A utility function to    // do inorder traversal of BST    void inorderRec(Node root)    {        if (root != null) {            inorderRec(root.left);            Console.Write(root.key + " ");            inorderRec(root.right);        }    }Â
    // Driver Code    public static void Main(String[] args)    {        BinarySearchTree tree = new BinarySearchTree();Â
        /* Let us create following BST              50           /    \          30     70         / \   / \       20  40 60  80 */        tree.insert(50);        tree.insert(30);        tree.insert(20);        tree.insert(40);        tree.insert(70);        tree.insert(60);        tree.insert(80);Â
        // Print inorder traversal of the BST        tree.inorder();    }}Â
// This code is contributed by aashish1995 |
Javascript
<script>// javascript program to demonstrate // insert operation in binary// search tree    /*     * Class containing left and right child of current node and key value     */    class Node {     constructor(item) {            this.key = item;            this.left = this.right = null;        }    }Â
    // Root of BST    var root = null;Â
    // This method mainly calls insertRec()    function insert(key) {        root = insertRec(root, key);    }Â
    // A recursive function to insert a new key in BST    function insertRec(root, key) {Â
        // If the tree is empty, return a new node        if (root == null) {            root = new Node(key);            return root;        }Â
        // Otherwise, recur down the tree        if (key < root.key)            root.left = insertRec(root.left, key);        else if (key > root.key)            root.right = insertRec(root.right, key);Â
        // Return the (unchanged) node pointer        return root;    }Â
    // This method mainly calls InorderRec()    function inorder() {        inorderRec(root);    }Â
    // A utility function to    // do inorder traversal of BST    function inorderRec(root)    {        if (root != null) {            inorderRec(root.left);            document.write(root.key+"<br/>");            inorderRec(root.right);        }    }Â
// Driver CodeÂ
        /* Let us create following BST              50           /    \          30     70         / \   / \       20  40 60  80 */        insert(50);        insert(30);        insert(20);        insert(40);        insert(70);        insert(60);        insert(80);Â
        // Print inorder traversal of the BST        inorder();Â
// This code is contributed by Rajput-Ji</script> |
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++
// C++ Code to insert node and to print inorder traversal// using iterationÂ
#include <bits/stdc++.h>using namespace std;Â
// BST Nodeclass Node {public:Â Â Â Â int val;Â Â Â Â Node* left;Â Â Â Â Node* right;Â Â Â Â Node(int val)Â Â Â Â Â Â Â Â : val(val)Â Â Â Â Â Â Â Â , left(NULL)Â Â Â Â Â Â Â Â , right(NULL)Â Â Â Â {Â Â Â Â }};Â
// Utility function to insert node in BSTvoid insert(Node*& root, int key){    Node* node = new Node(key);    if (!root) {        root = node;        return;    }    Node* prev = NULL;    Node* temp = root;    while (temp) {        if (temp->val > key) {            prev = temp;            temp = temp->left;        }        else if (temp->val < key) {            prev = temp;            temp = temp->right;        }    }    if (prev->val > key)        prev->left = node;    else        prev->right = node;}Â
// Utility function to print inorder traversalvoid inorder(Node* root){Â Â Â Â Node* temp = root;Â Â Â Â stack<Node*> st;Â Â Â Â while (temp != NULL || !st.empty()) {Â Â Â Â Â Â Â Â if (temp != NULL) {Â Â Â Â Â Â Â Â Â Â Â Â st.push(temp);Â Â Â Â Â Â Â Â Â Â Â Â temp = temp->left;Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â else {Â Â Â Â Â Â Â Â Â Â Â Â temp = st.top();Â Â Â Â Â Â Â Â Â Â Â Â st.pop();Â Â Â Â Â Â Â Â Â Â Â Â cout << temp->val << " ";Â Â Â Â Â Â Â Â Â Â Â Â temp = temp->right;Â Â Â Â Â Â Â Â }Â Â Â Â }}Â
// Driver codeint main(){Â Â Â Â Node* root = NULL;Â Â Â Â insert(root, 30);Â Â Â Â insert(root, 50);Â Â Â Â insert(root, 15);Â Â Â Â insert(root, 20);Â Â Â Â insert(root, 10);Â Â Â Â insert(root, 40);Â Â Â Â insert(root, 60);Â
    // Function call to print the inorder traversal    inorder(root);Â
    return 0;} |
Java
// Java code to implement the insertion// in binary search treeÂ
import java.io.*;import java.util.*;Â
class GFG {Â
    // Driver code    public static void main(String[] args)    {        BST tree = new BST();        tree.insert(30);        tree.insert(50);        tree.insert(15);        tree.insert(20);        tree.insert(10);        tree.insert(40);        tree.insert(60);Â
        tree.inorder();    }}Â
class Node {Â Â Â Â Node left;Â Â Â Â int val;Â Â Â Â Node right;Â Â Â Â Node(int val) { this.val = val; }}Â
class BST {Â Â Â Â Node root;Â
    // Function to insert a key    public void insert(int key)    {        Node node = new Node(key);        if (root == null) {            root = node;            return;        }        Node prev = null;        Node temp = root;        while (temp != null) {            if (temp.val > key) {                prev = temp;                temp = temp.left;            }            else if (temp.val < key) {                prev = temp;                temp = temp.right;            }        }        if (prev.val > key)            prev.left = node;        else            prev.right = node;    }Â
    // Function to print the inorder value    public void inorder()    {        Node temp = root;        Stack<Node> stack = new Stack<>();        while (temp != null || !stack.isEmpty()) {            if (temp != null) {                stack.add(temp);                temp = temp.left;            }            else {                temp = stack.pop();                System.out.print(temp.val + " ");                temp = temp.right;            }        }    }} |
Python3
# Python 3 code to implement the insertion# operation iterativelyÂ
Â
class GFG:    @staticmethod    def main(args):        tree = BST()        tree.insert(30)        tree.insert(50)        tree.insert(15)        tree.insert(20)        tree.insert(10)        tree.insert(40)        tree.insert(60)        tree.inorder()Â
Â
class Node:    left = None    val = 0    right = NoneÂ
    def __init__(self, val):        self.val = valÂ
Â
class BST:Â Â Â Â root = NoneÂ
    # Function to insert a key in the BST    def insert(self, key):        node = Node(key)        if (self.root == None):            self.root = node            return        prev = None        temp = self.root        while (temp != None):            if (temp.val > key):                prev = temp                temp = temp.left            elif(temp.val < key):                prev = temp                temp = temp.right        if (prev.val > key):            prev.left = node        else:            prev.right = nodeÂ
    # Function to print the inorder traversal of BSTÂ
    def inorder(self):        temp = self.root        stack = []        while (temp != None or not (len(stack) == 0)):            if (temp != None):                stack.append(temp)                temp = temp.left            else:                temp = stack.pop()                print(str(temp.val) + " ", end="")                temp = temp.rightÂ
Â
if __name__ == "__main__":Â Â Â Â GFG.main([])Â
Â
# This code is contributed by rastogik346. |
C#
// Function to implement the insertion// operation iterativelyÂ
using System;using System.Collections.Generic;Â
public class GFG {Â
    // Driver code    public static void Main(String[] args)    {        BST tree = new BST();        tree.insert(30);        tree.insert(50);        tree.insert(15);        tree.insert(20);        tree.insert(10);        tree.insert(40);        tree.insert(60);Â
        // Function call to print the inorder traversal        tree.inorder();    }}Â
public class Node {Â Â Â Â public Node left;Â Â Â Â public int val;Â Â Â Â public Node right;Â
    public Node(int val) { this.val = val; }}Â
public class BST {Â Â Â Â public Node root;Â
    // Function to insert a new key in the BST    public void insert(int key)    {        Node node = new Node(key);        if (root == null) {            root = node;            return;        }        Node prev = null;        Node temp = root;        while (temp != null) {            if (temp.val > key) {                prev = temp;                temp = temp.left;            }            else if (temp.val < key) {                prev = temp;                temp = temp.right;            }        }        if (prev.val > key)            prev.left = node;        else            prev.right = node;    }Â
    // Function to print the inorder traversal of BST    public void inorder()    {        Node temp = root;        Stack<Node> stack = new Stack<Node>();        while (temp != null || stack.Count != 0) {            if (temp != null) {                stack.Push(temp);                temp = temp.left;            }            else {                temp = stack.Pop();                Console.Write(temp.val + " ");                temp = temp.right;            }        }    }}Â
// This code is contributed by Rajput-Ji |
Javascript
// JavaScript code to implement the insertion// in binary search treeÂ
class Node {Â Â constructor(val) {Â Â Â Â this.left = null;Â Â Â Â this.val = val;Â Â Â Â this.right = null;Â Â }}Â
class BST {Â Â constructor() {Â Â Â Â this.root = null;Â Â }Â
  // Function to insert a key  insert(key) {    let node = new Node(key);    if (this.root == null) {      this.root = node;      return;    }    let prev = null;    let temp = this.root;    while (temp != null) {      if (temp.val > key) {        prev = temp;        temp = temp.left;      } else if (temp.val < key) {        prev = temp;        temp = temp.right;      }    }    if (prev.val > key) prev.left = node;    else prev.right = node;  }Â
  // Function to print the inorder value  inorder() {    let temp = this.root;    let stack = [];    while (temp != null || stack.length > 0) {      if (temp != null) {        stack.push(temp);        temp = temp.left;      } else {        temp = stack.pop();        console.log(temp.val + " ");        temp = temp.right;      }    }  }}Â
let tree = new BST();tree.insert(30);tree.insert(50);tree.insert(15);tree.insert(20);tree.insert(10);tree.insert(40);tree.insert(60);Â
tree.inorder();// this code is contributed by devendrasolunke |
10 15 20 30 40 50 60
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:Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
