How to insert a node in Binary Search Tree using Iteration

You are given a binary search tree (BST) and a value to insert into the tree. Print inorder traversal of the BST after the insertion.
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.Â
Approach:
As we all know that a new key is always inserted at the leaf node. so we 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 with the given value, while searching if the value of current node is greater then the given value then move to the left , else move to right
Follow the steps mentioned below to implement the idea:
- Start from the 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++
// 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 than 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
// Java program to demonstrate insert operation// in binary search treeimport java.util.*;class solution {Â
    // BST node    static class Node {        int key;        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 than 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);            System.out.print(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);    }}// contributed by Arnab Kundu |
Python3
"""Python3 program to demonstrate insert operation in binary search tree """Â
# A Binary Tree Node# Utility function to create a# new tree nodeÂ
Â
class 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 BSTÂ
Â
def 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 than 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 BSTÂ
Â
def 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#
// 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 than 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 |
Javascript
<script>Â
// javascript program to demonstrate insert // operation in binary search tree// BST node class Node {     constructor()    {        this.key = 0;        this.left = null;        this.right = null;    }}; Â
// Utility function to create a new node function 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 BST function 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 than 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 function 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 BST Inorder(root); Â
// This code is contributed by itsok.</script> |
20 30 40 50 60 70 80
Time Complexity: O(H), where H is the height of the BST.Â
Auxiliary Space: O(1)Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!




