Given the root of a 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: All the nodes have distinct values in the BST and the new value to be inserted is not present in the BST.
Example:
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, 4, N, 6] Explanation: After inserting the node 4, the new tree will be [2, 1, 3, N, N, N, 4, N, 6].
[Naive Approach] Recursive Insertion - O(h) Time and O(h) Space
The idea is to insert the new key at a position that preserves the Binary Search Tree (BST) property. Starting from the root, compare the key with the current node. If the key is smaller, move to the left child; otherwise, move to the right child. Continue this process until a NULL child is reached, then insert the new node at that position as a leaf node. This ensures that the BST property remains valid after the insertion.
C++
#include<iostream>#include<queue>#include<vector>usingnamespacestd;// Structure for a Binary Search Tree nodeclassNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Insert a node into the BSTNode*insert(Node*root,intkey){// If tree is empty, create a new nodeif(root==nullptr){returnnewNode(key);}// Insert into the left subtreeif(key<root->data){root->left=insert(root->left,key);}// Insert into the right subtreeelse{root->right=insert(root->right,key);}returnroot;}// Print the tree in level ordervoidprintTree(Node*root){if(root==nullptr){cout<<"[]";return;}vector<string>ans;queue<Node*>q;q.push(root);while(!q.empty()){Node*curr=q.front();q.pop();if(curr==nullptr){ans.push_back("N");}else{ans.push_back(to_string(curr->data));q.push(curr->left);q.push(curr->right);}}// Remove trailing N'swhile(!ans.empty()&&ans.back()=="N"){ans.pop_back();}cout<<"[";for(inti=0;i<ans.size();i++){cout<<ans[i];if(i+1<ans.size()){cout<<", ";}}cout<<"]";}intmain(){// Create the BST// 22// / \ // 12 30// / \ // 8 20// \ // 21Node*root=newNode(22);root->left=newNode(12);root->right=newNode(30);root->left->left=newNode(8);root->left->right=newNode(20);root->left->right->right=newNode(21);intkey=15;root=insert(root,key);printTree(root);return0;}
C
#include<stdio.h>#include<stdlib.h>// Structure for a Binary Search Tree nodestructNode{intdata;structNode*left;structNode*right;};structNode*createNode(intx){structNode*temp=(structNode*)malloc(sizeof(structNode));temp->data=x;temp->left=NULL;temp->right=NULL;returntemp;}// Insert a node into the BSTstructNode*insert(structNode*root,intkey){// If tree is empty, create a new nodeif(root==NULL){returncreateNode(key);}// Insert into the left subtreeif(key<root->data){root->left=insert(root->left,key);}// Insert into the right subtreeelse{root->right=insert(root->right,key);}returnroot;}// Print the tree in level ordervoidprintTree(structNode*root){if(root==NULL){printf("[]");return;}structNode*queue[100];charans[100][10];intfront=0,rear=0,size=0;queue[rear++]=root;while(front<rear){structNode*curr=queue[front++];if(curr==NULL){sprintf(ans[size++],"N");}else{sprintf(ans[size++],"%d",curr->data);queue[rear++]=curr->left;queue[rear++]=curr->right;}}// Remove trailing N'swhile(size>0&&strcmp(ans[size-1],"N")==0){size--;}printf("[");for(inti=0;i<size;i++){printf("%s",ans[i]);if(i+1<size){printf(", ");}}printf("]");}intmain(){// Create the BST// 22// / \ // 12 30// / \ // 8 20// \ // 21structNode*root=createNode(22);root->left=createNode(12);root->right=createNode(30);root->left->left=createNode(8);root->left->right=createNode(20);root->left->right->right=createNode(21);intkey=15;root=insert(root,key);printTree(root);return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;importjava.util.List;importjava.util.ArrayList;// Structure for a Binary Search Tree nodeclassNode{intdata;Nodeleft;Noderight;Node(intx){data=x;left=null;right=null;}}publicclassGFG{// Insert a node into the BSTstaticNodeinsert(Noderoot,intkey){// If tree is empty, create a new nodeif(root==null){returnnewNode(key);}// Insert into the left subtreeif(key<root.data){root.left=insert(root.left,key);}// Insert into the right subtreeelse{root.right=insert(root.right,key);}returnroot;}// Print the tree in level orderstaticvoidprintTree(Noderoot){if(root==null){System.out.print("[]");return;}ArrayList<String>ans=newArrayList<>();Queue<Node>q=newLinkedList<>();q.offer(root);while(!q.isEmpty()){Nodecurr=q.poll();if(curr==null){ans.add("N");}else{ans.add(String.valueOf(curr.data));q.offer(curr.left);q.offer(curr.right);}}// Remove trailing N'swhile(!ans.isEmpty()&&ans.get(ans.size()-1).equals("N")){ans.remove(ans.size()-1);}System.out.print("[");for(inti=0;i<ans.size();i++){System.out.print(ans.get(i));if(i+1<ans.size()){System.out.print(", ");}}System.out.print("]");}publicstaticvoidmain(String[]args){// Create the BST// 22// / \// 12 30// / \// 8 20// \// 21Noderoot=newNode(22);root.left=newNode(12);root.right=newNode(30);root.left.left=newNode(8);root.left.right=newNode(20);root.left.right.right=newNode(21);intkey=15;root=insert(root,key);printTree(root);}}
Python
fromcollectionsimportdeque# Structure for a Binary Search Tree nodeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Insert a node into the BSTdefinsert(root,key):# If tree is empty, create a new nodeifrootisNone:returnNode(key)# Insert into the left subtreeifkey<root.data:root.left=insert(root.left,key)# Insert into the right subtreeelse:root.right=insert(root.right,key)returnroot# Print the tree in level orderdefprintTree(root):ifrootisNone:print("[]")returnans=[]q=deque([root])whileq:curr=q.popleft()ifcurrisNone:ans.append("N")else:ans.append(str(curr.data))q.append(curr.left)q.append(curr.right)# Remove trailing N'swhileansandans[-1]=="N":ans.pop()print("["+", ".join(ans)+"]")if__name__=="__main__":# Create the BST# 22# / \# 12 30# / \# 8 20# \# 21root=Node(22)root.left=Node(12)root.right=Node(30)root.left.left=Node(8)root.left.right=Node(20)root.left.right.right=Node(21)key=15root=insert(root,key)printTree(root)
C#
usingSystem;usingSystem.Collections.Generic;// Structure for a Binary Search Tree nodeclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=null;right=null;}}classGFG{// Insert a node into the BSTstaticNodeinsert(Noderoot,intkey){// If tree is empty, create a new nodeif(root==null){returnnewNode(key);}// Insert into the left subtreeif(key<root.data){root.left=insert(root.left,key);}// Insert into the right subtreeelse{root.right=insert(root.right,key);}returnroot;}// Print the tree in level orderstaticvoidprintTree(Noderoot){if(root==null){Console.Write("[]");return;}List<string>ans=newList<string>();Queue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){Nodecurr=q.Dequeue();if(curr==null){ans.Add("N");}else{ans.Add(curr.data.ToString());q.Enqueue(curr.left);q.Enqueue(curr.right);}}// Remove trailing N'swhile(ans.Count>0&&ans[ans.Count-1]=="N"){ans.RemoveAt(ans.Count-1);}Console.Write("[");for(inti=0;i<ans.Count;i++){Console.Write(ans[i]);if(i+1<ans.Count){Console.Write(", ");}}Console.Write("]");}staticvoidMain(){// Create the BST// 22// / \// 12 30// / \// 8 20// \// 21Noderoot=newNode(22);root.left=newNode(12);root.right=newNode(30);root.left.left=newNode(8);root.left.right=newNode(20);root.left.right.right=newNode(21);intkey=15;root=insert(root,key);printTree(root);}}
Javascript
// Structure for a Binary Search Tree nodeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Insert a node into the BSTfunctioninsert(root,key){// If tree is empty, create a new nodeif(root===null){returnnewNode(key);}// Insert into the left subtreeif(key<root.data){root.left=insert(root.left,key);}// Insert into the right subtreeelse{root.right=insert(root.right,key);}returnroot;}// Print the tree in level orderfunctionprintTree(root){if(root===null){process.stdout.write("[]");return;}constans=[];constq=[root];while(q.length>0){constcurr=q.shift();if(curr===null){ans.push("N");}else{ans.push(curr.data.toString());q.push(curr.left);q.push(curr.right);}}// Remove trailing N'swhile(ans.length>0&&ans[ans.length-1]==="N"){ans.pop();}process.stdout.write("["+ans.join(", ")+"]");}// Driver code// Create the BST// 22// / \// 12 30// / \// 8 20// \// 21letroot=newNode(22);root.left=newNode(12);root.right=newNode(30);root.left.left=newNode(8);root.left.right=newNode(20);root.left.right.right=newNode(21);letkey=15;root=insert(root,key);printTree(root);
Output
[22, 12, 30, 8, 20, N, N, N, N, 15, 21]
[Expected Approach] Iterative Traversal - O(h) Time and O(1) Space
The idea is to iteratively traverse the BST to find the correct position for the new key. Starting from the root, move left if the key is smaller; otherwise, move right. When a NULL child is found, insert the new node there as a leaf node, preserving the BST property.
C++
#include<iostream>#include<queue>#include<vector>usingnamespacestd;// Structure for a Binary Search Tree nodeclassNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Insert a node into the BSTNode*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&&curr->left!=nullptr){curr=curr->left;}elseif(curr->data<key&&curr->right!=nullptr){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;}// Print the tree in level ordervoidprintTree(Node*root){if(root==nullptr){cout<<"[]";return;}vector<string>ans;queue<Node*>q;q.push(root);while(!q.empty()){Node*curr=q.front();q.pop();if(curr==nullptr){ans.push_back("N");}else{ans.push_back(to_string(curr->data));q.push(curr->left);q.push(curr->right);}}// Remove trailing N'swhile(!ans.empty()&&ans.back()=="N"){ans.pop_back();}cout<<"[";for(inti=0;i<ans.size();i++){cout<<ans[i];if(i+1<ans.size()){cout<<", ";}}cout<<"]";}intmain(){// Create the BST// 22// / \ // 12 30// / \ // 8 20// \ // 21Node*root=newNode(22);root->left=newNode(12);root->right=newNode(30);root->left->left=newNode(8);root->left->right=newNode(20);root->left->right->right=newNode(21);intkey=15;root=insert(root,key);printTree(root);return0;}
C
#include<stdio.h>#include<stdlib.h>#include<string.h>// Structure for a Binary Search Tree nodestructNode{intdata;structNode*left;structNode*right;};structNode*createNode(intx){structNode*temp=(structNode*)malloc(sizeof(structNode));temp->data=x;temp->left=NULL;temp->right=NULL;returntemp;}// Insert a node into the BSTstructNode*insert(structNode*root,intkey){structNode*temp=createNode(key);// If tree is emptyif(root==NULL){returntemp;}// Find the node who is going to// have the new node as its childstructNode*curr=root;while(curr!=NULL){if(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;}// Print the tree in level ordervoidprintTree(structNode*root){if(root==NULL){printf("[]");return;}structNode*q[100];charans[100][10];intfront=0,rear=0;intsize=0;q[rear++]=root;while(front<rear){structNode*curr=q[front++];if(curr==NULL){strcpy(ans[size++],"N");}else{sprintf(ans[size++],"%d",curr->data);q[rear++]=curr->left;q[rear++]=curr->right;}}// Remove trailing N'swhile(size>0&&strcmp(ans[size-1],"N")==0){size--;}printf("[");for(inti=0;i<size;i++){printf("%s",ans[i]);if(i+1<size){printf(", ");}}printf("]");}intmain(){// Create the BST// 22// / \ // 12 30// / \ // 8 20// \ // 21structNode*root=createNode(22);root->left=createNode(12);root->right=createNode(30);root->left->left=createNode(8);root->left->right=createNode(20);root->left->right->right=createNode(21);intkey=15;root=insert(root,key);printTree(root);return0;}
Java
importjava.util.ArrayList;importjava.util.LinkedList;importjava.util.Queue;// Structure for a Binary Search Tree nodeclassNode{intdata;Nodeleft;Noderight;Node(intx){data=x;left=null;right=null;}}publicclassMain{// Insert a node into the BSTstaticNodeinsert(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&&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;}// Print the tree in level orderstaticvoidprintTree(Noderoot){if(root==null){System.out.print("[]");return;}ArrayList<String>ans=newArrayList<>();Queue<Node>q=newLinkedList<>();q.offer(root);while(!q.isEmpty()){Nodecurr=q.poll();if(curr==null){ans.add("N");}else{ans.add(String.valueOf(curr.data));q.offer(curr.left);q.offer(curr.right);}}// Remove trailing N'swhile(!ans.isEmpty()&&ans.get(ans.size()-1).equals("N")){ans.remove(ans.size()-1);}System.out.print("[");for(inti=0;i<ans.size();i++){System.out.print(ans.get(i));if(i+1<ans.size()){System.out.print(", ");}}System.out.print("]");}publicstaticvoidmain(String[]args){// Create the BST// 22// / \// 12 30// / \// 8 20// \// 21Noderoot=newNode(22);root.left=newNode(12);root.right=newNode(30);root.left.left=newNode(8);root.left.right=newNode(20);root.left.right.right=newNode(21);intkey=15;root=insert(root,key);printTree(root);}}
Python
fromcollectionsimportdeque# Structure for a Binary Search Tree nodeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Insert a node into the BSTdefinsert(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>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=tempreturnroot# Print the tree in level orderdefprintTree(root):ifrootisNone:print("[]")returnans=[]q=deque([root])whileq:curr=q.popleft()ifcurrisNone:ans.append("N")else:ans.append(str(curr.data))q.append(curr.left)q.append(curr.right)# Remove trailing N'swhileansandans[-1]=="N":ans.pop()print("["+", ".join(ans)+"]")if__name__=="__main__":# Create the BST# 22# / \# 12 30# / \# 8 20# \# 21root=Node(22)root.left=Node(12)root.right=Node(30)root.left.left=Node(8)root.left.right=Node(20)root.left.right.right=Node(21)key=15root=insert(root,key)printTree(root)
C#
usingSystem;usingSystem.Collections.Generic;// Structure for a Binary Search Tree nodeclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=null;right=null;}}classGFG{// Insert a node into the BSTstaticNodeinsert(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&&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;}// Print the tree in level orderstaticvoidprintTree(Noderoot){if(root==null){Console.Write("[]");return;}List<string>ans=newList<string>();Queue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){Nodecurr=q.Dequeue();if(curr==null){ans.Add("N");}else{ans.Add(curr.data.ToString());q.Enqueue(curr.left);q.Enqueue(curr.right);}}// Remove trailing N'swhile(ans.Count>0&&ans[ans.Count-1]=="N"){ans.RemoveAt(ans.Count-1);}Console.Write("[");for(inti=0;i<ans.Count;i++){Console.Write(ans[i]);if(i+1<ans.Count){Console.Write(", ");}}Console.Write("]");}staticvoidMain(){// Create the BST// 22// / \// 12 30// / \// 8 20// \// 21Noderoot=newNode(22);root.left=newNode(12);root.right=newNode(30);root.left.left=newNode(8);root.left.right=newNode(20);root.left.right.right=newNode(21);intkey=15;root=insert(root,key);printTree(root);}}
Javascript
// Structure for a Binary Search Tree nodeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Insert a node into the BSTfunctioninsert(root,key){lettemp=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&&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;}// Print the tree in level orderfunctionprintTree(root){if(root===null){console.log("[]");return;}constans=[];constq=[root];while(q.length>0){constcurr=q.shift();if(curr===null){ans.push("N");}else{ans.push(curr.data.toString());q.push(curr.left);q.push(curr.right);}}// Remove trailing N'swhile(ans.length>0&&ans[ans.length-1]==="N"){ans.pop();}console.log("["+ans.join(", ")+"]");}// Driver code// Create the BST// 22// / \// 12 30// / \// 8 20// \// 21letroot=newNode(22);root.left=newNode(12);root.right=newNode(30);root.left.left=newNode(8);root.left.right=newNode(20);root.left.right.right=newNode(21);letkey=15;root=insert(root,key);printTree(root);