Deleting a node in a BST means removing the target node while ensuring that the tree remains a valid BST. Depending on the structure of the node to be deleted, there are three possible scenarios:
Case 1: Node has No Children (Leaf Node)
If the target node is a leaf node, it can be directly removed from the tree since it has no child to maintain.
Working:
Case 2: Node has One Child(Left or Right Child)
If the target node has only one child, we remove the node and connect its parent directly to its only child. This way, the tree remains valid after deletion of target node.
Working:
Case 3: Node has Two Children
If the target node has two children, deletion is slightly more complex.
To maintain the BST property, we need to find a replacement node for the target. The replacement can be either:
The inorder successor — the smallest value in the right subtree, which is the next greater value than the target node.
The inorder predecessor — the largest value in the left subtree, which is the next smaller value than the target node.
Once the replacement node is chosen, we replace the target node’s value with that node’s value, and then delete the replacement node, which will now fall under Case 1 (no children) or Case 2 (one child).
Note: Inorder predecessor can also be used.
Working:
The deletion process in BST depends on the number of children of the node.
No children means simply remove the node.
One child means remove the node and connect its parent to the node’s only child.
Two children means replace the node with its inorder successor/predecessor and delete that node.
This ensures that the BST property remains intact after every deletion.
C++
//Driver Code Starts#include<iostream>#include<vector>#include<unordered_map>#include<queue>usingnamespacestd;// Node structureclassNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Calculate HeightintgetHeight(Node*root,inth){if(root==nullptr)returnh-1;returnmax(getHeight(root->left,h+1),getHeight(root->right,h+1));}// Print Level OrdervoidlevelOrder(Node*root){queue<pair<Node*,int>>q;q.push({root,0});intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of treewhile(!q.empty()){autotop=q.front();q.pop();Node*node=top.first;intlvl=top.second;if(lvl>lastLevel){cout<<"";lastLevel=lvl;}// all levels are printedif(lvl>height)break;if(node->data!=-1)cout<<node->data<<" ";// printing null nodeelsecout<<"N ";// null node has no childrenif(node->data==-1)continue;if(node->left==nullptr)q.push({newNode(-1),lvl+1});elseq.push({node->left,lvl+1});if(node->right==nullptr)q.push({newNode(-1),lvl+1});elseq.push({node->right,lvl+1});}}//Driver Code Ends// Get inorder successor (smallest in right subtree)Node*getSuccessor(Node*curr){curr=curr->right;while(curr!=nullptr&&curr->left!=nullptr)curr=curr->left;returncurr;}// Delete a node with value x from BSTNode*delNode(Node*root,intx){if(root==nullptr)returnroot;if(root->data>x)root->left=delNode(root->left,x);elseif(root->data<x)root->right=delNode(root->right,x);else{// Node with 0 or 1 childif(root->left==nullptr){Node*temp=root->right;deleteroot;returntemp;}if(root->right==nullptr){Node*temp=root->left;deleteroot;returntemp;}// Node with 2 childrenNode*succ=getSuccessor(root);root->data=succ->data;root->right=delNode(root->right,succ->data);}returnroot;}//Driver Code Startsintmain(){Node*root=newNode(10);root->left=newNode(5);root->right=newNode(15);root->right->left=newNode(12);root->right->right=newNode(18);intx=15;root=delNode(root,x);levelOrder(root);return0;}//Driver Code Ends
C
//Driver Code Starts#include<stdio.h>#include<stdlib.h>// Node structurestructNode{intdata;structNode*left;structNode*right;};// Function to create a new nodestructNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->left=newNode->right=NULL;returnnewNode;}// Function to find the height of the treeintgetHeight(structNode*root,inth){if(root==NULL)returnh-1;intleftHeight=getHeight(root->left,h+1);intrightHeight=getHeight(root->right,h+1);return(leftHeight>rightHeight)?leftHeight:rightHeight;}// Queue structure for level order traversalstructQueueNode{structNode*node;intlevel;};structQueue{structQueueNodearr[100];intfront,rear;};// Initialize queuevoidinitQueue(structQueue*q){q->front=0;q->rear=0;}// Enqueuevoidenqueue(structQueue*q,structNode*node,intlevel){q->arr[q->rear].node=node;q->arr[q->rear].level=level;q->rear++;}// DequeuestructQueueNodedequeue(structQueue*q){returnq->arr[q->front++];}// Check if queue is emptyintisEmpty(structQueue*q){returnq->front==q->rear;}// Function to print Level Order TraversalvoidlevelOrder(structNode*root){if(root==NULL)return;structQueueq;initQueue(&q);enqueue(&q,root,0);intlastLevel=0;// function to get height of the treeintheight=getHeight(root,0);// printing level order of the treewhile(!isEmpty(&q)){structQueueNodetemp=dequeue(&q);structNode*node=temp.node;intlvl=temp.level;if(lvl>lastLevel){printf("");lastLevel=lvl;}// all levels are printedif(lvl>height)break;// Printing null nodesif(node->data!=-1)printf("%d ",node->data);elseprintf("N ");// null node has no childrenif(node->data==-1)continue;if(node->left==NULL)enqueue(&q,createNode(-1),lvl+1);elseenqueue(&q,node->left,lvl+1);if(node->right==NULL)enqueue(&q,createNode(-1),lvl+1);elseenqueue(&q,node->right,lvl+1);}}//Driver Code Ends// the inorder successor (smallest in right subtree)structNode*getSuccessor(structNode*curr){curr=curr->right;while(curr!=NULL&&curr->left!=NULL)curr=curr->left;returncurr;}// Function to delete a node with value x from BSTstructNode*delNode(structNode*root,intx){if(root==NULL)returnroot;if(root->data>x)root->left=delNode(root->left,x);elseif(root->data<x)root->right=delNode(root->right,x);else{// Node with 0 or 1 childif(root->left==NULL){structNode*temp=root->right;free(root);returntemp;}if(root->right==NULL){structNode*temp=root->left;free(root);returntemp;}// Node with 2 childrenstructNode*succ=getSuccessor(root);root->data=succ->data;root->right=delNode(root->right,succ->data);}returnroot;}//Driver Code Startsintmain(){structNode*root=createNode(10);root->left=createNode(5);root->right=createNode(15);root->right->left=createNode(12);root->right->right=createNode(18);intx=15;root=delNode(root,x);levelOrder(root);return0;}//Driver Code Ends
Java
//Driver Code Startsimportjava.util.LinkedList;importjava.util.Queue;importjava.util.List;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.Map;// Node structureclassNode{intdata;Nodeleft,right;publicNode(intitem){data=item;left=right=null;}}classGfG{// Calculate HeightstaticintgetHeight(Noderoot,inth){if(root==null)returnh-1;returnMath.max(getHeight(root.left,h+1),getHeight(root.right,h+1));}// Print Level OrderstaticvoidlevelOrder(Noderoot){Queue<List<Object>>queue=newLinkedList<>();queue.offer(List.of(root,0));intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of treewhile(!queue.isEmpty()){List<Object>top=queue.poll();Nodenode=(Node)top.get(0);intlvl=(int)top.get(1);if(lvl>lastLevel){System.out.println();lastLevel=lvl;}// all levels are printedif(lvl>height)break;// printing null nodeSystem.out.print((node.data==-1?"N":node.data)+" ");// null node has no childrenif(node.data==-1)continue;if(node.left==null)queue.offer(List.of(newNode(-1),lvl+1));elsequeue.offer(List.of(node.left,lvl+1));if(node.right==null)queue.offer(List.of(newNode(-1),lvl+1));elsequeue.offer(List.of(node.right,lvl+1));}}//Driver Code Ends// Get inorder successor (smallest in right subtree)staticNodegetSuccessor(Nodecurr){curr=curr.right;while(curr!=null&&curr.left!=null){curr=curr.left;}returncurr;}// Delete a node with value x from BSTstaticNodedelNode(Noderoot,intx){if(root==null)returnroot;if(root.data>x){root.left=delNode(root.left,x);}elseif(root.data<x){root.right=delNode(root.right,x);}else{// Node with 0 or 1 childif(root.left==null)returnroot.right;if(root.right==null)returnroot.left;// Node with 2 childrenNodesucc=getSuccessor(root);root.data=succ.data;root.right=delNode(root.right,succ.data);}returnroot;}//Driver Code Startspublicstaticvoidmain(String[]args){Noderoot=newNode(10);root.left=newNode(5);root.right=newNode(15);root.right.left=newNode(12);root.right.right=newNode(18);intx=15;root=delNode(root,x);levelOrder(root);}}//Driver Code Ends
Python
#Driver Code Startsfromcollectionsimportdeque# Node structureclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Calculate HeightdefgetHeight(root,h):ifrootisNone:returnh-1returnmax(getHeight(root.left,h+1),getHeight(root.right,h+1))# Print Level OrderdeflevelOrder(root):q=deque()q.append((root,0))lastLevel=0# function to get the height of treeheight=getHeight(root,0)# printing the level order of treewhileq:node,lvl=q.popleft()iflvl>lastLevel:print()lastLevel=lvl# all levels are printediflvl>height:break# printing null nodesifnode.data!=-1:print(node.data,end=" ")else:print("N",end=" ")# null node has no childrenifnode.data==-1:continueifnode.leftisNone:q.append((Node(-1),lvl+1))else:q.append((node.left,lvl+1))ifnode.rightisNone:q.append((Node(-1),lvl+1))else:q.append((node.right,lvl+1))#Driver Code Ends# Get inorder successor (smallest in right subtree)defgetSuccessor(curr):curr=curr.rightwhilecurrisnotNoneandcurr.leftisnotNone:curr=curr.leftreturncurr# Delete a node with value x from BSTdefdelNode(root,x):ifrootisNone:returnrootifroot.data>x:root.left=delNode(root.left,x)elifroot.data<x:root.right=delNode(root.right,x)else:# node with 0 or 1 childrenifroot.leftisNone:returnroot.rightifroot.rightisNone:returnroot.left# Node with 2 childrensucc=getSuccessor(root)root.data=succ.dataroot.right=delNode(root.right,succ.data)returnroot#Driver Code Startsif__name__=="__main__":root=Node(10)root.left=Node(5)root.right=Node(15)root.right.left=Node(12)root.right.right=Node(18)x=15root=delNode(root,x)levelOrder(root)#Driver Code Ends
C#
//Driver Code StartsusingSystem;usingSystem.Collections.Generic;// Node structureclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Calculate HeightstaticintgetHeight(Noderoot,inth){if(root==null)returnh-1;returnMath.Max(getHeight(root.left,h+1),getHeight(root.right,h+1));}// Print Level OrderstaticvoidlevelOrder(Noderoot){Queue<(Node,int)>q=newQueue<(Node,int)>();q.Enqueue((root,0));intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of the treewhile(q.Count>0){var(node,lvl)=q.Dequeue();if(lvl>lastLevel){Console.WriteLine();lastLevel=lvl;}//all levels are printedif(lvl>height)break;// printing null nodesif(node.data!=-1)Console.Write(node.data+" ");elseConsole.Write("N ");// null node has no childrenif(node.data==-1)continue;if(node.left==null)q.Enqueue((newNode(-1),lvl+1));elseq.Enqueue((node.left,lvl+1));if(node.right==null)q.Enqueue((newNode(-1),lvl+1));elseq.Enqueue((node.right,lvl+1));}}//Driver Code Ends// Get inorder successor (smallest in right subtree)staticNodegetSuccessor(Nodecurr){curr=curr.right;while(curr!=null&&curr.left!=null)curr=curr.left;returncurr;}// Delete a node with value x from BSTstaticNodedelNode(Noderoot,intx){if(root==null)returnroot;if(root.data>x)root.left=delNode(root.left,x);elseif(root.data<x)root.right=delNode(root.right,x);else{// Node with 0 or 1 childif(root.left==null)returnroot.right;if(root.right==null)returnroot.left;// Node with 2 childrenNodesucc=getSuccessor(root);root.data=succ.data;root.right=delNode(root.right,succ.data);}returnroot;}//Driver Code StartsstaticvoidMain(){Noderoot=newNode(10);root.left=newNode(5);root.right=newNode(15);root.right.left=newNode(12);root.right.right=newNode(18);intx=15;root=delNode(root,x);levelOrder(root);}}//Driver Code Ends
JavaScript
//Driver Code StartsconstDenque=require("denque");// Node structureclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Calculate HeightfunctiongetHeight(root,h){if(root===null)returnh-1;returnMath.max(getHeight(root.left,h+1),getHeight(root.right,h+1));}// Print Level OrderfunctionlevelOrder(root){constq=newDenque();q.push([root,0]);letlastLevel=0;// function to get height of the treeconstheight=getHeight(root,0);// printing level order of the treewhile(!q.isEmpty()){const[node,lvl]=q.shift();if(lvl>lastLevel){console.log();lastLevel=lvl;}// all levels are printedif(lvl>height)break;// printing null nodesif(node.data!==-1)process.stdout.write(node.data+" ");elseprocess.stdout.write("N ");// null node has no childrenif(node.data===-1)continue;if(node.left===null)q.push([newNode(-1),lvl+1]);elseq.push([node.left,lvl+1]);if(node.right===null)q.push([newNode(-1),lvl+1]);elseq.push([node.right,lvl+1]);}}//Driver Code Ends// Get inorder successor (smallest in right subtree)functiongetSuccessor(curr){curr=curr.right;while(curr!==null&&curr.left!==null)curr=curr.left;returncurr;}// Delete a node with value x from BSTfunctiondelNode(root,x){if(root===null)returnroot;if(root.data>x)root.left=delNode(root.left,x);elseif(root.data<x)root.right=delNode(root.right,x);else{// Node with 0 or 1 childif(root.left===null)returnroot.right;if(root.right===null)returnroot.left;// Node with 2 childrenconstsucc=getSuccessor(root);root.data=succ.data;root.right=delNode(root.right,succ.data);}returnroot;}//Driver Code Starts// Driver codeletroot=newNode(10);root.left=newNode(5);root.right=newNode(15);root.right.left=newNode(12);root.right.right=newNode(18);constx=15;root=delNode(root,x);levelOrder(root);//Driver Code Ends
Output
10
5 18
N N 12 N
Time Complexity: O(h), where h is the height of the BST. Auxiliary Space: O(h).