Given a binary tree and a key, the task is to insert the key into the binary tree at the first position available in level order manner.
Examples:
Input: key = 12
Output:
Explanation: Node with value 12 is inserted into the binary tree at the first position available in level order manner.
Approach:
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
Below is the implementation of the above approach:
C++
// C++ program to insert element (in level order)// in Binary Tree#include<iostream>#include<queue>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Function to insert element in binary treeNode*InsertNode(Node*root,intdata){// If the tree is empty, assign new// node address to rootif(root==nullptr){root=newNode(data);returnroot;}// 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()){// Fron a front element in queueNode*curr=q.front();q.pop();// First check left if left is null // insert node in left otherwise chaeck for rightif(curr->left!=nullptr)q.push(curr->left);else{curr->left=newNode(data);returnroot;}if(curr->right!=nullptr)q.push(curr->right);else{curr->right=newNode(data);returnroot;}}}// Inorder traversal of a binary tree voidinorder(Node*curr){if(curr==nullptr)return;inorder(curr->left);cout<<curr->data<<' ';inorder(curr->right);}intmain(){// Constructing the binary tree// 10// / \ // 11 9// / / \ // 7 15 8Node*root=newNode(10);root->left=newNode(11);root->right=newNode(9);root->left->left=newNode(7);root->right->left=newNode(15);root->right->right=newNode(8);intkey=12;root=InsertNode(root,key);// After insertion 12 in binary tree// 10// / \ // 11 9// / \ / \ // 7 12 15 8inorder(root);return0;}
Java
// Java program to insert element (in level order)// in Binary Treeimportjava.util.LinkedList;importjava.util.Queue;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Function to insert element // in binary treestaticNodeInsertNode(Noderoot,intdata){// If the tree is empty, assign new node // address to rootif(root==null){root=newNode(data);returnroot;}// 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=newLinkedList<>();q.add(root);while(!q.isEmpty()){// Fron a front element in queueNodecurr=q.poll();// First check left if left is null insert// node in left otherwise chaeck for rightif(curr.left!=null)q.add(curr.left);else{curr.left=newNode(data);returnroot;}if(curr.right!=null)q.add(curr.right);else{curr.right=newNode(data);returnroot;}}returnroot;}// Inorder traversal of a binary treestaticvoidinorder(Nodecurr){if(curr==null)return;inorder(curr.left);System.out.print(curr.data+" ");inorder(curr.right);}publicstaticvoidmain(String[]args){// Constructing the binary tree// 10// / \ // 11 9// / / \// 7 15 8Noderoot=newNode(10);root.left=newNode(11);root.right=newNode(9);root.left.left=newNode(7);root.right.left=newNode(15);root.right.right=newNode(8);intkey=12;root=InsertNode(root,key);// After insertion 12 in binary tree// 10// / \ // 11 9// / \ / \// 7 12 15 8inorder(root);}}
Python
# Python program to insert element (in level order)# in Binary TreefromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to insert element # in binary treedefInsertNode(root,data):# If the tree is empty, assign new# node address to rootifrootisNone:root=Node(data)returnroot# 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.q=deque()q.append(root)whileq:# Fron a front element # in queuecurr=q.popleft()# First check left if left is null # insert node in left otherwise check# for rightifcurr.leftisnotNone:q.append(curr.left)else:curr.left=Node(data)returnrootifcurr.rightisnotNone:q.append(curr.right)else:curr.right=Node(data)returnroot# Inorder traversal of a binary treedefinorder(curr):ifcurrisNone:returninorder(curr.left)print(curr.data,end=' ')inorder(curr.right)if__name__=="__main__":# Constructing the binary tree# 10# / \ # 11 9# / / \# 7 15 8root=Node(10)root.left=Node(11)root.right=Node(9)root.left.left=Node(7)root.right.left=Node(15)root.right.right=Node(8)key=12root=InsertNode(root,key)# After insertion 12 in binary tree# 10# / \ # 11 9# / \ / \# 7 12 15 8inorder(root)
C#
// C# program to insert element (in level order)// in Binary TreeusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to insert element in binary treestaticNodeInsertNode(Noderoot,intdata){// If the tree is empty, assign new node// address to rootif(root==null){root=newNode(data);returnroot;}// 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=newQueue<Node>();q.Enqueue(root);while(q.Count>0){// Fron a front element in queueNodecurr=q.Dequeue();// First check left if left is null// insert node in left otherwise check // for rightif(curr.left!=null)q.Enqueue(curr.left);else{curr.left=newNode(data);returnroot;}if(curr.right!=null)q.Enqueue(curr.right);else{curr.right=newNode(data);returnroot;}}returnroot;}// Inorder traversal of a binary treestaticvoidinorder(Nodecurr){if(curr==null)return;inorder(curr.left);Console.Write(curr.data+" ");inorder(curr.right);}staticvoidMain(string[]args){// Constructing the binary tree// 10// / \ // 11 9// / / \// 7 15 8Noderoot=newNode(10);root.left=newNode(11);root.right=newNode(9);root.left.left=newNode(7);root.right.left=newNode(15);root.right.right=newNode(8);intkey=12;root=InsertNode(root,key);// After insertion 12 in binary tree// 10// / \ // 11 9// / \ / \// 7 12 15 8inorder(root);}}
JavaScript
// JavaScript program to insert element // (in level order) in Binary TreeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to insert element in binary treefunctionInsertNode(root,data){// If the tree is empty, assign new// node address to rootif(root==null){root=newNode(data);returnroot;}// 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.letq=[];q.push(root);while(q.length>0){letcurr=q.shift();// First check left if left is null // insert node in left otherwise chaeck for rightif(curr.left!==null)q.push(curr.left);else{curr.left=newNode(data);returnroot;}if(curr.right!==null)q.push(curr.right);else{curr.right=newNode(data);returnroot;}}}// Inorder traversal of a binary treefunctioninorder(curr){if(curr==null)return;inorder(curr.left);process.stdout.write(curr.data+' ');inorder(curr.right);}// Constructing the binary tree// 10// / \ // 11 9// / / \// 7 15 8letroot=newNode(10);root.left=newNode(11);root.right=newNode(9);root.left.left=newNode(7);root.right.left=newNode(15);root.right.right=newNode(8);letkey=12;root=InsertNode(root,key);// After insertion 12 in binary tree// 10// / \ // 11 9// / \ / \// 7 12 15 8inorder(root);
Output
7 11 12 10 15 9 8
Time Complexity: O(n) where n is the number of nodes. Auxiliary Space: O(n)
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
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.