Insert a node in Binary Search Tree Iteratively

18 Aug, 2021
A recursive approach to insert a new node in a BST is already discussed in the post: Binary Search Tree | SET 1. In this post, an iterative approach to insert a node in BST is discussed. 
Insertion of a Key
A new key is always inserted at the leaf node. Start searching a key from root till we hit a leaf node. Once a leaf node is found, the new node is added as a child of the leaf node.Example:  
Input:To the given BST insert 40  
Output:  
Explanation:The new node 40 is a leaf node. Start searching from the root till a leaf node is hit, i.e while searching if a new value is greater than current node move to right child else to left child. Input:To the given BST insert 600  
Output:  
Explanation:The new node 600 is a leaf node. Start searching from the root till a leaf node is hit, i.e while searching if a new value is greater than current node move to right child else to left child.  
 
Solution: Approach:  
It is to be noted that new keys are always inserted at the leaf node.
Start from root and run a loop until a null pointer is reached.
Keep the previous pointer of the current node stored.
If the current node is null then create and insert the new node there and make it as one of the children of the parent/previous node depending on its value.
If the value of current node is less than the new value then move to the right child of current node else move to the left child.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ program to demonstrate insert operation// in binary search tree#include <bits/stdc++.h>using namespace std; // BST nodestruct Node {    int key;    struct Node *left, *right;}; // Utility function to create a new nodeNode* newNode(int data){    Node* temp = new Node;     temp->key = data;     temp->left = NULL;    temp->right = NULL;     return temp;} // A utility function to insert a new// Node with given key in BSTNode* insert(Node* root, int key){    // Create a new Node containing    // the new element    Node* newnode = newNode(key);     // Pointer to start traversing from root and    // traverses downward path to search    // where the new node to be inserted    Node* x = root;     // Pointer y maintains the trailing    // pointer of x    Node* y = NULL;     while (x != NULL) {        y = x;        if (key < x->key)            x = x->left;        else            x = x->right;    }     // If the root is NULL i.e the tree is empty    // The new node is the root node    if (y == NULL)        y = newnode;     // If the new key is less then the leaf node key    // Assign the new node to be its left child    else if (key < y->key)        y->left = newnode;     // else assign the new node its right child    else        y->right = newnode;     // Returns the pointer where the    // new node is inserted    return y;} // A utility function to do inorder// traversal of BSTvoid Inorder(Node* root){    if (root == NULL)        return;    else {        Inorder(root->left);        cout << root->key << " ";        Inorder(root->right);    }} // Driver codeint main(){    /* Let us create following BST            50          /   \        30      70        / \   / \       20 40 60 80 */     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 program to demonstrate insert operation// in binary search treeimport java.util.*;class solution{   // BST nodestatic class Node {    int key;     Node left, right;};   // Utility function to create a new nodestatic Node newNode(int data){    Node temp = new Node();       temp.key = data;       temp.left = null;    temp.right = null;       return temp;}   // A utility function to insert a new// Node with given key in BSTstatic Node insert(Node root, int key){    // Create a new Node containing    // the new element    Node newnode = newNode(key);       // Pointer to start traversing from root and    // traverses downward path to search    // where the new node to be inserted    Node x = root;       // Pointer y maintains the trailing    // pointer of x    Node y = null;       while (x != null) {        y = x;        if (key < x.key)            x = x.left;        else            x = x.right;    }       // If the root is null i.e the tree is empty    // The new node is the root node    if (y == null)        y = newnode;       // If the new key is less then the leaf node key    // Assign the new node to be its left child    else if (key < y.key)        y.left = newnode;       // else assign the new node its right child    else        y.right = newnode;       // Returns the pointer where the    // new node is inserted    return y;}   // A utility function to do inorder// traversal of BSTstatic void Inorder(Node root){    if (root == null)        return;    else {        Inorder(root.left);        System.out.print( root.key +" ");        Inorder(root.right);    }}   // Driver codepublic static void main(String args[]){    /* Let us create following BST             50           /   \         30      70         / \   / \        20 40 60 80 */       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);   }}//contributed by Arnab Kundu
"""Python3 program to demonstrate insertoperation in binary search tree """ # A Binary Tree Node# Utility function to create a# new tree nodeclass newNode:     # Constructor to create a newNode    def __init__(self, data):        self.key= data        self.left = None        self.right = self.parent = None # A utility function to insert a new# Node with given key in BSTdef insert(root, key):     # Create a new Node containing    # the new element    newnode = newNode(key)     # Pointer to start traversing from root    # and traverses downward path to search    # where the new node to be inserted    x = root     # Pointer y maintains the trailing    # pointer of x    y = None     while (x != None):        y = x        if (key < x.key):            x = x.left        else:            x = x.right         # If the root is None i.e the tree is    # empty. The new node is the root node    if (y == None):        y = newnode     # If the new key is less then the leaf node key    # Assign the new node to be its left child    elif (key < y.key):        y.left = newnode     # else assign the new node its    # right child    else:        y.right = newnode     # Returns the pointer where the    # new node is inserted    return y # A utility function to do inorder# traversal of BSTdef Inorder(root) :     if (root == None) :        return    else:        Inorder(root.left)        print( root.key, end = " " )        Inorder(root.right)                         # Driver Codeif __name__ == '__main__':     """ Let us create following BST            50        / \        30     70        / \ / \    20 40 60 80 """     root = None    root = insert(root, 50)    insert(root, 30)    insert(root, 20)    insert(root, 40)    insert(root, 70)    insert(root, 60)    insert(root, 80)     # Pr inorder traversal of the BST    Inorder(root) # This code is contributed by# SHUBHAMSINGH10
// C# program to demonstrate insert // operation in binary search treeusing System; class GFG{    // BST node    class Node    {        public int key;        public Node left, right;    };     // Utility function to create a new node    static Node newNode(int data)    {        Node temp = new Node();         temp.key = data;         temp.left = null;        temp.right = null;         return temp;    }     // A utility function to insert a new    // Node with given key in BST    static Node insert(Node root, int key)    {        // Create a new Node containing        // the new element        Node newnode = newNode(key);         // Pointer to start traversing from root and        // traverses downward path to search        // where the new node to be inserted        Node x = root;         // Pointer y maintains the trailing        // pointer of x        Node y = null;         while (x != null)        {            y = x;            if (key < x.key)                x = x.left;            else                x = x.right;        }         // If the root is null i.e the tree is empty        // The new node is the root node        if (y == null)            y = newnode;         // If the new key is less then the leaf node key        // Assign the new node to be its left child        else if (key < y.key)            y.left = newnode;         // else assign the new node its right child        else            y.right = newnode;         // Returns the pointer where the        // new node is inserted        return y;    }     // A utility function to do inorder    // traversal of BST    static void Inorder(Node root)    {        if (root == null)            return;        else        {            Inorder(root.left);            Console.Write( root.key +" ");            Inorder(root.right);        }    }     // Driver code    public static void Main(String []args)    {        /* Let us create following BST                50            / \            30 70            / \ / \        20 40 60 80 */         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);    }} // This code is contributed 29AjayKumar
<script> // javascript program to demonstrate insert // operation in binary search tree// BST nodeclass Node{    constructor()    {        this.key = 0;        this.left = null;        this.right = null;    }}; // Utility function to create a new nodefunction newNode(data){    var temp = new Node();    temp.key = data;    temp.left = null;    temp.right = null;    return temp;} // A utility function to insert a new// Node with given key in BSTfunction insert(root, key){     // Create a new Node containing    // the new element    var newnode = newNode(key);         // Pointer to start traversing from root and    // traverses downward path to search    // where the new node to be inserted    var x = root;         // Pointer y maintains the trailing    // pointer of x    var y = null;     while (x != null)    {        y = x;        if (key < x.key)            x = x.left;        else            x = x.right;    }         // If the root is null i.e the tree is empty    // The new node is the root node    if (y == null)        y = newnode;             // If the new key is less then the leaf node key    // Assign the new node to be its left child    else if (key < y.key)        y.left = newnode;             // else assign the new node its right child    else        y.right = newnode;             // Returns the pointer where the    // new node is inserted    return y;} // A utility function to do inorder// traversal of BSTfunction Inorder(root){    if (root == null)        return;    else    {        Inorder(root.left);        document.write( root.key +" ");        Inorder(root.right);    }} // Driver code/* Let us create following BST        50    / \    30 70    / \ / \20 40 60 80 */var 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 BSTInorder(root); // This code is contributed by itsok.</script>
20 30 40 50 60 70 80
 
Complexity Analysis:  
Time Complexity : O(h), where h is height of binary search tree. In worst case the height is equal to number of nodes.
 
Space Complexity: O(1), no extra space is required.
 
andrew1234
29AjayKumar
SHUBHAMSINGH10
Ongfa
itsok
saurabh1990aror
gabaa406
Data Structures-Tree Traversals
Picked
Binary Search Tree
Tree
Binary Search Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
set vs unordered_set in C++ STL
Flatten BST to sorted list | Increasing order
Largest BST in a Binary Tree | Set 2
Find median of BST in O(n) time and O(1) space
Floor and Ceil from a BST
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Introduction to Data Structures
Introduction to Tree Data Structure