Given a root of Binary Search Tree (BST) and an integer key, insert a new node with value key into the BST. Return the root of the modified tree after the insertion.
Note: If the key is already present in the BST, return the root.
Examples:
Input: root = [2, 1, 3], key = 4
Output: [2, 1, 3, N, N, N, 4] Explanation: After inserting the node 4, the new tree will be [2, 1, 3, N, N, N, 4].
Input: root = [2, 1, 3, N, N, N, 6], key = 4
Output: [2, 1, 3, N, N, N, 6, 4] Explanation: After inserting the node 4, the new tree will be [2, 1, 3, N, N, N, 6, 4].
[Naive Approach] Using Recursive Insertion - O(h) Time and O(h) Space
The idea is to compare the key with the current node and based on comparison result, recursively move left or right until an empty position is found.
Working of Approach:
Start from the root node and compare the key with the current node's value.
If the key is already present, return the current root without inserting a duplicate.
If the key is smaller, recursively insert it into the left subtree.
Otherwise, recursively insert it into the right subtree.
When a nullptr position is reached, create and insert the new node at that position.
C++
#include<iostream>#include<queue>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};Node*insert(Node*root,intkey){// Insert the new node at an empty positionif(root==nullptr)returnnewNode(key);// If key is already present, do not insert it againif(key==root->data)returnroot;// Insert into the left subtreeif(key<root->data)root->left=insert(root->left,key);// Insert into the right subtreeelseroot->right=insert(root->right,key);returnroot;}intmain(){// Create the BSTNode*root=newNode(2);root->left=newNode(1);root->right=newNode(3);root->right->right=newNode(6);intkey=4;root=insert(root,key);// Print level orderqueue<Node*>q;q.push(root);cout<<"[";boolfirst=true;while(!q.empty()){Node*curr=q.front();q.pop();if(!first)cout<<", ";first=false;if(curr){cout<<curr->data;q.push(curr->left);q.push(curr->right);}else{cout<<"N";}}cout<<"]";return0;}
Java
importjava.util.*;classNode{intdata;Nodeleft;Noderight;Node(intval){data=val;left=right=null;}}classGFG{staticNodeinsert(Noderoot,intkey){// Insert the new node at an empty positionif(root==null)returnnewNode(key);// If key is already present, do not insert it againif(key==root.data)returnroot;// Insert into the left subtreeif(key<root.data)root.left=insert(root.left,key);// Insert into the right subtreeelseroot.right=insert(root.right,key);returnroot;}publicstaticvoidmain(String[]args){// Create the BSTNoderoot=newNode(2);root.left=newNode(1);root.right=newNode(3);root.right.right=newNode(6);intkey=4;root=insert(root,key);// Print level orderQueue<Node>q=newLinkedList<>();q.offer(root);System.out.print("[");booleanfirst=true;while(!q.isEmpty()){Nodecurr=q.poll();if(!first)System.out.print(", ");first=false;if(curr!=null){System.out.print(curr.data);q.offer(curr.left);q.offer(curr.right);}else{System.out.print("N");}}System.out.print("]");}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=Nonedefinsert(root,key):# Insert the new node at an empty positionifrootisNone:returnNode(key)# If key is already present, do not insert it againifkey==root.data:returnroot# Insert into the left subtreeifkey<root.data:root.left=insert(root.left,key)# Insert into the right subtreeelse:root.right=insert(root.right,key)returnrootif__name__=="__main__":# Create the BSTroot=Node(2)root.left=Node(1)root.right=Node(3)root.right.right=Node(6)key=4root=insert(root,key)# Print level orderq=deque([root])print("[",end="")first=Truewhileq:curr=q.popleft()ifnotfirst:print(", ",end="")first=Falseifcurr:print(curr.data,end="")q.append(curr.left)q.append(curr.right)else:print("N",end="")print("]")
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}classGFG{staticNodeinsert(Noderoot,intkey){// Insert the new node at an empty positionif(root==null)returnnewNode(key);// If key is already present, do not insert it againif(key==root.data)returnroot;// Insert into the left subtreeif(key<root.data)root.left=insert(root.left,key);// Insert into the right subtreeelseroot.right=insert(root.right,key);returnroot;}publicstaticvoidMain(){// Create the BSTNoderoot=newNode(2);root.left=newNode(1);root.right=newNode(3);root.right.right=newNode(6);intkey=4;root=insert(root,key);// Print level orderQueue<Node>q=newQueue<Node>();q.Enqueue(root);Console.Write("[");boolfirst=true;while(q.Count>0){Nodecurr=q.Dequeue();if(!first)Console.Write(", ");first=false;if(curr!=null){Console.Write(curr.data);q.Enqueue(curr.left);q.Enqueue(curr.right);}else{Console.Write("N");}}Console.Write("]");}}
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functioninsert(root,key){// Insert the new node at an empty positionif(root===null)returnnewNode(key);// If key is already present, do not insert it againif(key===root.data)returnroot;// Insert into the left subtreeif(key<root.data)root.left=insert(root.left,key);// Insert into the right subtreeelseroot.right=insert(root.right,key);returnroot;}// Driver Code// Create the BSTletroot=newNode(2);root.left=newNode(1);root.right=newNode(3);root.right.right=newNode(6);constkey=4;root=insert(root,key);// Print level orderconstq=[root];letfront=0;letres=[];letfirst=true;while(front<q.length){constcurr=q[front++];if(!first)res.push(", ");first=false;if(curr!==null){res.push(curr.data);q.push(curr.left);q.push(curr.right);}else{res.push("N");}}console.log("["+res.join("")+"]");
Output
[2, 1, 3, N, N, N, 6, 4, N, N, N]
[Expected Approach] Using Iterative Traversal - O(h) Time and O(1) Space
The idea is to compare the key with the current node and based on comparison result, iteratively move left or right until an empty position is found.
Working of Approach:
Create a new node temp containing the given key.
If the BST is empty, return temp as the root.
Otherwise, start from the root and traverse the BST.
If the key is already present, return the root without inserting a duplicate.
If the key is smaller than the current node, move to the left subtree.
If the key is greater, move to the right subtree.
When an appropriate empty position is found, attach the new node as either the left or right child.
Let us understand with an example: Input: root = [2, 1, 3, N, N, N, 6], key = 4
Start with root = 2 and key = 4.
Since 4 > 2, move to the right child 3.
Since 4 > 3, move to the right child 6.
Since 4 < 6 and the left child of 6 is NULL, stop the traversal.
Insert 4 as the left child of 6.
The final BST in level-order representation is [2, 1, 3, N, N, N, 6, 4].
C++
#include<iostream>#include<queue>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};Node*insert(Node*root,intkey){Node*temp=newNode(key);// If tree is emptyif(root==nullptr){returntemp;}// Find the node who is going to// have the new node as its childNode*curr=root;while(curr!=nullptr){if(curr->data==key){returnroot;}elseif(curr->data>key&&curr->left!=nullptr){curr=curr->left;}elseif(curr->data<key&&curr->right!=nullptr){curr=curr->right;}elsebreak;}// If key is smaller, make it left// child, else right childif(curr->data>key){curr->left=temp;}else{curr->right=temp;}returnroot;}intmain(){// Create the BSTNode*root=newNode(2);root->left=newNode(1);root->right=newNode(3);root->right->right=newNode(6);intkey=4;root=insert(root,key);// Print level orderqueue<Node*>q;q.push(root);cout<<"[";boolfirst=true;while(!q.empty()){Node*curr=q.front();q.pop();if(!first)cout<<", ";first=false;if(curr){cout<<curr->data;q.push(curr->left);q.push(curr->right);}else{cout<<"N";}}cout<<"]";return0;}
Java
importjava.util.*;classNode{intdata;Nodeleft;Noderight;Node(intval){data=val;left=right=null;}}classGFG{staticNodeinsert(Noderoot,intkey){Nodetemp=newNode(key);// If tree is emptyif(root==null){returntemp;}// Find the node who is going to// have the new node as its childNodecurr=root;while(curr!=null){if(curr.data==key){returnroot;}elseif(curr.data>key&&curr.left!=null){curr=curr.left;}elseif(curr.data<key&&curr.right!=null){curr=curr.right;}else{break;}}// If key is smaller, make it left// child, else right childif(curr.data>key){curr.left=temp;}else{curr.right=temp;}returnroot;}publicstaticvoidmain(String[]args){// Create the BSTNoderoot=newNode(2);root.left=newNode(1);root.right=newNode(3);root.right.right=newNode(6);intkey=4;root=insert(root,key);// Print level orderQueue<Node>q=newLinkedList<>();q.offer(root);System.out.print("[");booleanfirst=true;while(!q.isEmpty()){Nodecurr=q.poll();if(!first){System.out.print(", ");}first=false;if(curr!=null){System.out.print(curr.data);q.offer(curr.left);q.offer(curr.right);}else{System.out.print("N");}}System.out.print("]");}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=Nonedefinsert(root,key):temp=Node(key)# If tree is emptyifrootisNone:returntemp# Find the node who is going to# have the new node as its childcurr=rootwhilecurrisnotNone:ifcurr.data==key:returnrootelifcurr.data>keyandcurr.leftisnotNone:curr=curr.leftelifcurr.data<keyandcurr.rightisnotNone:curr=curr.rightelse:break# If key is smaller, make it left# child, else right childifcurr.data>key:curr.left=tempelse:curr.right=tempreturnrootif__name__=="__main__":# Create the BSTroot=Node(2)root.left=Node(1)root.right=Node(3)root.right.right=Node(6)key=4root=insert(root,key)# Print level orderq=deque([root])res=[]first=Truewhileq:curr=q.popleft()ifnotfirst:res.append(", ")first=FalseifcurrisnotNone:res.append(str(curr.data))q.append(curr.left)q.append(curr.right)else:res.append("N")print("["+"".join(res)+"]")
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}classGFG{staticNodeinsert(Noderoot,intkey){Nodetemp=newNode(key);// If tree is emptyif(root==null){returntemp;}// Find the node who is going to// have the new node as its childNodecurr=root;while(curr!=null){if(curr.data==key){returnroot;}elseif(curr.data>key&&curr.left!=null){curr=curr.left;}elseif(curr.data<key&&curr.right!=null){curr=curr.right;}else{break;}}// If key is smaller, make it left// child, else right childif(curr.data>key){curr.left=temp;}else{curr.right=temp;}returnroot;}publicstaticvoidMain(){// Create the BSTNoderoot=newNode(2);root.left=newNode(1);root.right=newNode(3);root.right.right=newNode(6);intkey=4;root=insert(root,key);// Print level orderQueue<Node>q=newQueue<Node>();q.Enqueue(root);Console.Write("[");boolfirst=true;while(q.Count>0){Nodecurr=q.Dequeue();if(!first){Console.Write(", ");}first=false;if(curr!=null){Console.Write(curr.data);q.Enqueue(curr.left);q.Enqueue(curr.right);}else{Console.Write("N");}}Console.Write("]");}}
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functioninsert(root,key){consttemp=newNode(key);// If tree is emptyif(root===null){returntemp;}// Find the node who is going to// have the new node as its childletcurr=root;while(curr!==null){if(curr.data===key){returnroot;}elseif(curr.data>key&&curr.left!==null){curr=curr.left;}elseif(curr.data<key&&curr.right!==null){curr=curr.right;}else{break;}}// If key is smaller, make it left// child, else right childif(curr.data>key){curr.left=temp;}else{curr.right=temp;}returnroot;}// Driver Code// Create the BSTletroot=newNode(2);root.left=newNode(1);root.right=newNode(3);root.right.right=newNode(6);constkey=4;root=insert(root,key);// Print level orderconstq=[root];letfront=0;letres=[];letfirst=true;while(front<q.length){constcurr=q[front++];if(!first){res.push(", ");}first=false;if(curr!==null){res.push(curr.data);q.push(curr.left);q.push(curr.right);}else{res.push("N");}}console.log("["+res.join("")+"]");