Given a binary tree, the task is to delete a given node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with the last element.
Examples :
Input : key = 10
Output:
Explanation: As the bottom & rightmost node in the above binary tree is 30 , replace the key node ie. 10 with 30 and remove the bottom & rightmost node.
Input : key = 20
Output:
Explanation: As the bottom & rightmost node in the above binary tree is 40, replace the key node ie. 20 with 40 and remove the bottom & rightmost node.
Approach:
The idea is to traverse the tree in level order manner. To perform the Deletion in a Binary Tree follow below:
Starting at the root, find the deepest and rightmost node in the binary tree and the node which we want to delete.
Replace the deepest rightmost node’s data with the node to be deleted.
Then delete the deepest rightmost node.
Below is the illustration of above approach:
Below is the implementation of the above approach:
C++
// C++ program to delete a specific element// in a binary tree#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Function to delete the deepest node in binary treevoiddeletDeepest(Node*root,Node*dNode){queue<Node*>q;q.push(root);Node*curr;while(!q.empty()){curr=q.front();q.pop();// If current node is the deepest// node, delete itif(curr==dNode){curr=nullptr;delete(dNode);return;}// Check the right child firstif(curr->right){// If right child is the deepest// node, delete itif(curr->right==dNode){curr->right=nullptr;delete(dNode);return;}q.push(curr->right);}// Check the left childif(curr->left){// If left child is the deepest // node, delete itif(curr->left==dNode){curr->left=nullptr;delete(dNode);return;}q.push(curr->left);}}}// Function to delete the node with the given keyNode*deletion(Node*root,intkey){// If the tree is empty, return nullif(root==nullptr)returnnullptr;// If the tree has only one nodeif(root->left==nullptr&&root->right==nullptr){// If the root node is the key, delete itif(root->data==key)returnnullptr;elsereturnroot;}queue<Node*>q;q.push(root);Node*curr;Node*keyNode=nullptr;// Level order traversal to find the deepest// node and the key nodewhile(!q.empty()){curr=q.front();q.pop();// If current node is the key nodeif(curr->data==key)keyNode=curr;if(curr->left)q.push(curr->left);if(curr->right)q.push(curr->right);}// If key node is found, replace its data// with the deepest nodeif(keyNode!=nullptr){// Store the data of the deepest nodeintx=curr->data;// Replace key node data with deepest// node's datakeyNode->data=x;// Delete the deepest nodedeletDeepest(root,curr);}returnroot;}// Inorder traversal of a binary treevoidinorder(Node*curr){if(!curr)return;inorder(curr->left);cout<<curr->data<<" ";inorder(curr->right);}intmain(){// Construct the binary tree// 10 // / \ // 11 9// / \ / \ // 7 12 15 8 Node*root=newNode(10);root->left=newNode(11);root->right=newNode(9);root->left->left=newNode(7);root->left->right=newNode(12);root->right->left=newNode(15);root->right->right=newNode(8);intkey=11;root=deletion(root,key);inorder(root);return0;}
Java
// Java program to delete a specific // element in a binary treeimportjava.util.LinkedList;importjava.util.Queue;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Function to delete the deepest node in// binary treestaticvoiddeletDeepest(Noderoot,NodedNode){Queue<Node>q=newLinkedList<>();q.add(root);Nodecurr;while(!q.isEmpty()){curr=q.poll();// If current node is the deepest // node, delete itif(curr==dNode){curr=null;dNode=null;return;}// Check the right child firstif(curr.right!=null){// If right child is the deepest node,// delete itif(curr.right==dNode){curr.right=null;dNode=null;return;}q.add(curr.right);}// Check the left childif(curr.left!=null){// If left child is the deepest node,// delete itif(curr.left==dNode){curr.left=null;dNode=null;return;}q.add(curr.left);}}}// Function to delete the node with the given keystaticNodedeletion(Noderoot,intkey){if(root==null)returnnull;// If the tree has only one nodeif(root.left==null&&root.right==null){// If the root node is the key, // delete itif(root.data==key)returnnull;elsereturnroot;}Queue<Node>q=newLinkedList<>();q.add(root);Nodecurr=null;NodekeyNode=null;// Level order traversal to find the // deepest node and the key nodewhile(!q.isEmpty()){curr=q.poll();// If current node is the key nodeif(curr.data==key)keyNode=curr;if(curr.left!=null)q.add(curr.left);if(curr.right!=null)q.add(curr.right);}// If key node is found, replace its// data with the deepest nodeif(keyNode!=null){// Store the data of the// deepest nodeintx=curr.data;// Replace key node data with // deepest node's datakeyNode.data=x;// Delete the deepest nodedeletDeepest(root,curr);}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){// Construct the binary tree// 10 // / \ // 11 9// / \ / \ // 7 12 15 8 Noderoot=newNode(10);root.left=newNode(11);root.right=newNode(9);root.left.left=newNode(7);root.left.right=newNode(12);root.right.left=newNode(15);root.right.right=newNode(8);intkey=11;root=deletion(root,key);inorder(root);}}
Python
# Python program to delete a specific # element in a binary treeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to delete the deepest node# in the binary treedefdelete_deepest(root,dNode):queue=[root]whilequeue:curr=queue.pop(0)# If current node is the deepest # node, delete itifcurr==dNode:curr=NonedeldNodereturn# Check the right child firstifcurr.right:# If right child is the deepest# node, delete itifcurr.right==dNode:curr.right=NonedeldNodereturnqueue.append(curr.right)# Check the left childifcurr.left:# If left child is the deepest# node, delete itifcurr.left==dNode:curr.left=NonedeldNodereturnqueue.append(curr.left)# Function to delete the node with the given keydefdeletion(root,key):ifrootisNone:returnNone# If the tree has only one nodeifroot.leftisNoneandroot.rightisNone:ifroot.data==key:returnNoneelse:returnrootqueue=[root]curr=NonekeyNode=None# Level order traversal to find the# deepest node and the key nodewhilequeue:curr=queue.pop(0)# If current node is the key nodeifcurr.data==key:keyNode=currifcurr.left:queue.append(curr.left)ifcurr.right:queue.append(curr.right)# If key node is found, replace its# data with the deepest nodeifkeyNodeisnotNone:x=curr.data# Replace key node data with # deepest node's datakeyNode.data=x# Delete the deepest nodedelete_deepest(root,curr)returnroot# Inorder traversal of a binary treedefinorder(curr):ifcurrisNone:returninorder(curr.left)print(curr.data,end=" ")inorder(curr.right)if__name__=="__main__":# Construct the binary tree# 10 # / \ # 11 9# / \ / \ # 7 12 15 8 root=Node(10)root.left=Node(11)root.right=Node(9)root.left.left=Node(7)root.left.right=Node(12)root.right.left=Node(15)root.right.right=Node(8)key=11root=deletion(root,key)inorder(root)
C#
// C# program to delete a specific// element in a binary treeusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to delete the deepest node in binary treestaticvoiddeletDeepest(Noderoot,NodedNode){Queue<Node>q=newQueue<Node>();q.Enqueue(root);Nodecurr;while(q.Count>0){curr=q.Dequeue();// If current node is the deepest// node, delete itif(curr==dNode){curr=null;dNode=null;return;}// Check the right child firstif(curr.right!=null){if(curr.right==dNode){curr.right=null;dNode=null;return;}q.Enqueue(curr.right);}// Check the left childif(curr.left!=null){if(curr.left==dNode){curr.left=null;dNode=null;return;}q.Enqueue(curr.left);}}}// Function to delete the node with the given keystaticNodedeletion(Noderoot,intkey){if(root==null)returnnull;// If the tree has only one nodeif(root.left==null&&root.right==null){if(root.data==key)returnnull;elsereturnroot;}Queue<Node>q=newQueue<Node>();q.Enqueue(root);Nodecurr=null;Nodekey_node=null;// Level order traversal to find the// deepest node and the key nodewhile(q.Count>0){curr=q.Dequeue();// If current node is the key nodeif(curr.data==key)key_node=curr;if(curr.left!=null)q.Enqueue(curr.left);if(curr.right!=null)q.Enqueue(curr.right);}// If key node is found, replace // its data with the deepest nodeif(key_node!=null){// Store the data of the deepest nodeintx=curr.data;// Replace key node data with deepest // node's datakey_node.data=x;// Delete the deepest nodedeletDeepest(root,curr);}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){// Construct the binary tree// 10 // / \ // 11 9// / \ / \ // 7 12 15 8 Noderoot=newNode(10);root.left=newNode(11);root.right=newNode(9);root.left.left=newNode(7);root.left.right=newNode(12);root.right.left=newNode(15);root.right.right=newNode(8);intkey=11;root=deletion(root,key);inorder(root);}}
JavaScript
// JavaScript program to delete a specific // element in a binary treeclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Function to delete the deepest node in // a binary treefunctiondeleteDeepest(root,dNode){letqueue=[];queue.push(root);while(queue.length!==0){letcurr=queue.shift();// If current node is the deepest// node, delete itif(curr===dNode){curr=null;return;}// Check the right child firstif(curr.right){if(curr.right===dNode){curr.right=null;return;}else{queue.push(curr.right);}}// Check the left childif(curr.left){if(curr.left===dNode){curr.left=null;return;}else{queue.push(curr.left);}}}}// Function to delete the node with the given keyfunctiondeletion(root,key){if(root===null)returnnull;// If the tree has only one nodeif(root.left===null&&root.right===null){if(root.data===key)returnnull;elsereturnroot;}letqueue=[];queue.push(root);letkeyNode=null;letcurr=null;// Level order traversal to find the // deepest node and the key nodewhile(queue.length!==0){curr=queue.shift();// If current node is the key nodeif(curr.data===key)keyNode=curr;if(curr.left)queue.push(curr.left);if(curr.right)queue.push(curr.right);}// If the key node is found, replace its data// with the deepest node's dataif(keyNode!==null){// Store the deepest node's dataletx=curr.data;// Replace the key node's data with the// deepest node's datakeyNode.data=x;// Delete the deepest nodedeleteDeepest(root,curr);}returnroot;}// Inorder traversal of a binary treefunctioninorder(curr){if(curr===null)return;inorder(curr.left);console.log(curr.data+" ");inorder(curr.right);}// Construct the binary treeletroot=newNode(10);root.left=newNode(11);root.right=newNode(9);root.left.left=newNode(7);root.left.right=newNode(12);root.right.left=newNode(15);root.right.right=newNode(8);letkey=11;root=deletion(root,key);inorder(root);
Output
7 8 12 10 15 9
Time complexity: O(n), where n is number of nodes. Auxiliary Space: O(n)
Note: We can also replace the node's data that is to be deleted with any node whose left and right child points to NULL but we only use deepest node in order to maintain the Balance of a binary tree.
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.