The Wayback Machine - https://web.archive.org/web/20240625052642/https://www.geeksforgeeks.org/insertion-in-a-binary-tree-in-level-order/
Open In App

Insertion in a Binary Tree in level order

Last Updated : 16 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary tree and a key, insert the key into the binary tree at the first position available in level order.

The idea is to do an iterative level order traversal of the given tree using queue. If we find a node whose left child is empty, we make a new key as the left child of the node. Else if we find a node whose right child is empty, we make the new key as the right child. We keep traversing the tree until we find a node whose either left or right child is empty. 

C++




// C++ program to insert element in Binary Tree
#include <iostream>
#include <queue>
using namespace std;
 
/* A binary tree node has data, pointer to left child
and a pointer to right child */
 
struct Node {
    int data;
    Node* left;
    Node* right;
};
 
// Function to create a new node
Node* CreateNode(int data)
{
    Node* newNode = new Node();
    if (!newNode) {
        cout << "Memory error\n";
        return NULL;
    }
    newNode->data = data;
    newNode->left = newNode->right = NULL;
    return newNode;
}
 
// Function to insert element in binary tree
Node* InsertNode(Node* root, int data)
{
    // If the tree is empty, assign new node address to root
    if (root == NULL) {
        root = CreateNode(data);
        return root;
    }
 
    // Else, do level order traversal until we find an empty
    // place, i.e. either left child or right child of some
    // node is pointing to NULL.
    queue<Node*> q;
    q.push(root);
 
    while (!q.empty()) {
        Node* temp = q.front();
        q.pop();
 
        if (temp->left != NULL)
            q.push(temp->left);
        else {
            temp->left = CreateNode(data);
            return root;
        }
 
        if (temp->right != NULL)
            q.push(temp->right);
        else {
            temp->right = CreateNode(data);
            return root;
        }
    }
}
 
/* Inorder traversal of a binary tree */
 
void inorder(Node* temp)
{
    if (temp == NULL)
        return;
 
    inorder(temp->left);
    cout << temp->data << ' ';
    inorder(temp->right);
}
 
// Driver code
int main()
{
    Node* root = CreateNode(10);
    root->left = CreateNode(11);
    root->left->left = CreateNode(7);
    root->right = CreateNode(9);
    root->right->left = CreateNode(15);
    root->right->right = CreateNode(8);
 
    cout << "Inorder traversal before insertion: ";
    inorder(root);
    cout << endl;
 
    int key = 12;
    root = InsertNode(root, key);
 
    cout << "Inorder traversal after insertion: ";
    inorder(root);
    cout << endl;
 
    return 0;
}


Java




// Java program to insert element in binary tree
import java.util.LinkedList;
import java.util.Queue;
public class GFG {
 
    /* A binary tree node has key, pointer to
    left child and a pointer to right child */
    static class Node {
        int key;
        Node left, right;
 
        // constructor
        Node(int key)
        {
            this.key = key;
            left = null;
            right = null;
        }
    }
    static Node root;
    static Node temp = root;
 
    /* Inorder traversal of a binary tree*/
    static void inorder(Node temp)
    {
        if (temp == null)
            return;
 
        inorder(temp.left);
        System.out.print(temp.key + " ");
        inorder(temp.right);
    }
 
    /*function to insert element in binary tree */
    static void insert(Node temp, int key)
    {
 
        if (temp == null) {
            root = new Node(key);
            return;
        }
        Queue<Node> q = new LinkedList<Node>();
        q.add(temp);
 
        // Do level order traversal until we find
        // an empty place.
        while (!q.isEmpty()) {
            temp = q.peek();
            q.remove();
 
            if (temp.left == null) {
                temp.left = new Node(key);
                break;
            }
            else
                q.add(temp.left);
 
            if (temp.right == null) {
                temp.right = new Node(key);
                break;
            }
            else
                q.add(temp.right);
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        root = new Node(10);
        root.left = new Node(11);
        root.left.left = new Node(7);
        root.right = new Node(9);
        root.right.left = new Node(15);
        root.right.right = new Node(8);
 
        System.out.print(
            "Inorder traversal before insertion:");
        inorder(root);
 
        int key = 12;
        insert(root, key);
 
        System.out.print(
            "\nInorder traversal after insertion:");
        inorder(root);
    }
}
// This code is contributed by Sumit Ghosh


Python3




# Python program to insert element in binary tree
class newNode():
 
    def __init__(self, data):
        self.key = data
        self.left = None
        self.right = None
         
""" Inorder traversal of a binary tree"""
def inorder(temp):
 
    if (not temp):
        return
 
    inorder(temp.left)
    print(temp.key,end = " ")
    inorder(temp.right)
 
 
"""function to insert element in binary tree """
def insert(temp,key):
 
    if not temp:
        root = newNode(key)
        return
    q = []
    q.append(temp)
 
    # Do level order traversal until we find
    # an empty place.
    while (len(q)):
        temp = q[0]
        q.pop(0)
 
        if (not temp.left):
            temp.left = newNode(key)
            break
        else:
            q.append(temp.left)
 
        if (not temp.right):
            temp.right = newNode(key)
            break
        else:
            q.append(temp.right)
     
# Driver code
if __name__ == '__main__':
    root = newNode(10)
    root.left = newNode(11)
    root.left.left = newNode(7)
    root.right = newNode(9)
    root.right.left = newNode(15)
    root.right.right = newNode(8)
 
    print("Inorder traversal before insertion:", end = " ")
    inorder(root)
 
    key = 12
    insert(root, key)
 
    print()
    print("Inorder traversal after insertion:", end = " ")
    inorder(root)
 
# This code is contributed by SHUBHAMSINGH10


C#




// C# program to insert element in binary tree
using System;
using System.Collections.Generic;
 
class GFG {
 
    /* A binary tree node has key, pointer to
    left child and a pointer to right child */
    public class Node {
        public int key;
        public Node left, right;
 
        // constructor
        public Node(int key)
        {
            this.key = key;
            left = null;
            right = null;
        }
    }
    static Node root;
 
    /* Inorder traversal of a binary tree*/
    static void inorder(Node temp)
    {
        if (temp == null)
            return;
 
        inorder(temp.left);
        Console.Write(temp.key + " ");
        inorder(temp.right);
    }
 
    /*function to insert element in binary tree */
    static void insert(Node temp, int key)
    {
          if (temp == null) {
            root = new Node(key);
            return;
        }
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(temp);
 
        // Do level order traversal until we find
        // an empty place.
        while (q.Count != 0) {
            temp = q.Peek();
            q.Dequeue();
 
            if (temp.left == null) {
                temp.left = new Node(key);
                break;
            }
            else
                q.Enqueue(temp.left);
 
            if (temp.right == null) {
                temp.right = new Node(key);
                break;
            }
            else
                q.Enqueue(temp.right);
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        root = new Node(10);
        root.left = new Node(11);
        root.left.left = new Node(7);
        root.right = new Node(9);
        root.right.left = new Node(15);
        root.right.right = new Node(8);
 
        Console.Write(
            "Inorder traversal before insertion:");
        inorder(root);
 
        int key = 12;
        insert(root, key);
 
        Console.Write(
            "\nInorder traversal after insertion:");
        inorder(root);
    }
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
// javascript program to insert element in binary tree
 
    /*
     * A binary tree node has key, pointer to left child and a pointer to right
     * child
     */
class Node {
    constructor(val) {
        this.key = val;
        this.left = null;
        this.right = null;
    }
}
 
    var temp;
 
    /* Inorder traversal of a binary tree */
    function inorder(temp) {
        if (temp == null)
            return;
 
        inorder(temp.left);
        document.write(temp.key + " ");
        inorder(temp.right);
    }
 
    /* function to insert element in binary tree */
    function insert(temp , key) {
 
        if (temp == null) {
            root = new Node(key);
            return;
        }
        var q = [];
        q.push(temp);
 
        // Do level order traversal until we find
        // an empty place.
        while (q.length!=0) {
            temp = q.shift();
             
 
            if (temp.left == null) {
                temp.left = new Node(key);
                break;
            } else
                q.push(temp.left);
 
            if (temp.right == null) {
                temp.right = new Node(key);
                break;
            } else
                q.push(temp.right);
        }
    }
 
    // Driver code
        var root = new Node(10);
        root.left = new Node(11);
        root.left.left = new Node(7);
        root.right = new Node(9);
        root.right.left = new Node(15);
        root.right.right = new Node(8);
 
        document.write("Inorder traversal before insertion:");
        inorder(root);
 
        var key = 12;
        insert(root, key);
 
        document.write("<br\>Inorder traversal after insertion:");
        inorder(root);
 
// This code is contributed by umadevi9616
</script>


Output

Inorder traversal before insertion: 7 11 10 15 9 8 
Inorder traversal after insertion: 7 11 12 10 15 9 8 

Time Complexity:  O(V) where V is the number of nodes.
Auxiliary Space: O(B), where B is the width of the tree and in the worst case we need to hold all vertices of a level in the queue.



Previous Article
Next Article

Similar Reads

Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
Given a Binary Search Tree, the task is to print the nodes of the BST in the following order: If the BST contains levels numbered from 1 to N then, the printing order is level 1, level N, level 2, level N - 1, and so on.The top-level order (1, 2, …) nodes are printed from left to right, while the bottom level order (N, N-1, ...) nodes are printed f
15+ min read
Insertion in n-ary tree in given order and Level order traversal
Given a set of parent nodes where the index of the array is the child of each Node value, the task is to insert the nodes as a forest(multiple trees combined together) where each parent could have more than two children. After inserting the nodes, print each level in a sorted format. Example: Input: arr[] = {5, 3, -1, 2, 5, 3} Output:-1 231 5Input:
10 min read
Flatten Binary Tree in order of Level Order Traversal
Given a Binary Tree, the task is to flatten it in order of Level order traversal of the tree. In the flattened binary tree, the left node of all the nodes must be NULL.Examples: Input: 1 / \ 5 2 / \ / \ 6 4 9 3 Output: 1 5 2 6 4 9 3 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 1 2 3 4 5 Approach: We will solve this problem by simulating the Level order travers
7 min read
Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
Given a binary tree, print it vertically. The following example illustrates vertical order traversal. 1 / \ 2 3 / \ / \ 4 5 6 7 \ \ 8 9 The output of print this tree vertically will be: 4 2 1 5 6 3 8 7 9 We have discussed an efficient approach in below post.Print a Binary Tree in Vertical Order | Set 2 (Hashmap based Method)The above solution uses
10 min read
Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
Given the level order traversal of a Complete Binary Tree, determine whether the Binary Tree is a valid Min-Heap Examples: Input : level = [10, 15, 14, 25, 30] Output : True The tree of the given level order traversal is 10 / \ 15 14 / \ 25 30 We see that each parent has a value less than its child, and hence satisfies the min-heap property Input :
6 min read
Pre Order, Post Order and In Order traversal of a Binary Tree in one traversal | (Using recursion)
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order in one iteration. Examples: Input: Output: Pre Order: 1 2 4 5 3 6 7 Post Order: 4 5 2 6 7 3 1 In Order: 4 2 5 1 6 3 7 Input: Output: Pre Order: 1 2 4 8 12 5 9 3 6 7 10 11 Post Order: 12 8 4 9 5 2 6 10 11 7 3 1 In Order: 8 12 4 2 9 5 1 6
9 min read
Minimum value to be added at each level in Binary Tree to make all level sum equal
Given a binary tree, the task is to find all minimum values greater than or equal to zero, that should be added at each level to make the sum at each level equal. Examples: Input: 1 / \ 2 3 / \ 4 5 Output: 8 4 0Explanation: Initial sum at each level is {1, 5, 9}. To make all levels sum equal minimum values to be added are {8, 4, 0}. So the final su
9 min read
Print the nodes corresponding to the level value for each level of a Binary Tree
Given a Binary Tree, the task for each level L is to print the Lth node of the tree. If the Lth node is not present for any level, print -1. Note: Consider the root node to be at the level 1 of the binary tree. Examples: Input: Below is the given Tree: Output:Level 1: 1Level 2: 3 Level 3: 6Level 4: 11Explanation:For the first level, the 1st node is
15 min read
Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
Given a Binary Tree, the task is for each level is to print the total number of nodes from all lower levels which are less than or equal to every node present at that level. Examples: Input: Below is the given tree: 4 / \ 3 5 / \ / \ 10 2 3 1 Output: 4 3 0Explanation:Nodes in level 1 has 4 nodes as (3) in level 2 and (2, 3, 1) in level 3. Nodes in
11 min read
Modify a Binary Tree by adding a level of nodes with given value at a specified level
Given a Binary Tree consisting of N nodes and two integers K and L, the task is to add one row of nodes of value K at the Lth level, such that the orientation of the original tree remains unchanged. Examples: Input: K = 1, L = 2 Output:11 12 34 5 6 Explanation:Below is the tree after inserting node with value 1 in the K(= 2) th level. Input: K = 1,
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg