Deletion in a Binary Tree | Practice | GeeksforGeeks

Given a Binary Tree of size N, your task is to complete the function deletionBT(), that should delete a given node from the tree by making sure that tree shrinks from the bottom (the deleted node is replaced by bottommost and rightmost node).
Example:

Your Task:
You don't have to take input. Complete the function deletionBT() that takes root node of the tree and given node value (Key) as input parameter and return the root of the modified tree.

Example 1:
 
Input:
Key=1
         1
       /   \
      4     7
     / \
    5   6 
Output:
5 4 6 7 

Explanation:
Modified Tree after deletion the 
node with key = 1
     6 
    /  \
   4    7
  /   
 5     
The Inorder traversal of the modified 
tree is 5 4 6 7 



Constraints:
1<=N<=104
0
yaashh3 months ago
# this is the python solution which take O(N) time and O(N) space complexity.
 
from collections import deque
def deletionBT(root, key):   q=deque([root])   cur,node,par=None,None,None   while q:       cur=q.popleft()       if cur.data==key:           node=cur       if cur.left:           par=cur           q.append(cur.left)       if cur.right:           par=cur           q.append(cur.right)   node.data=cur.data   if par.right:par.right=None   else:par.left=None   return root
0
yaashh
This comment was deleted.
+10
tauruas08057 months ago
 queue<Node*>q;q.push(root);Node *tmp=NULL,*t,*p;  while(!q.empty()){       t=q.front();q.pop();      if(t->data==key)tmp=t;      if(t->left){          p=t;          q.push(t->left);      }      if(t->right){          p=t;q.push(t->right);      }  }  if(tmp!=NULL){      if(p->left==t)p->left=NULL;      else p->right=NULL;      tmp->data=t->data;      delete(t);  }  return root;
0
Sahil Shroff8 months ago
Sahil Shroff
void dfs(Node* root, vector<pair<node*, int="">> &travs, int lvl = 0) {    if (root == NULL)        return;    travs.push_back({root, lvl});    dfs(root->left, travs, lvl+1);    dfs(root->right, travs, lvl+1);}// you are required to complete this functionstruct Node* deletionBT(struct Node* root, int key){    // code here    vector<pair<node*, int="">> travs;    dfs(root, travs);    int mxl = -1, pdprni = -1;    Node *dprn = NULL, *keypos = NULL;    for (int i = 0; i < travs.size(); i++) {        if (travs[i].second >= mxl) {            mxl = travs[i].second;            dprn = travs[i].first;        }    }    for (int i = 0; i < travs.size(); i++) {        if (travs[i].first->left == dprn ||                 travs[i].first->right == dprn) {            pdprni = i;        }    }    /*for (int i = 0; i < travs.size(); i++) {        if (travs[i].second == mxl-1) {            pdprni == i        } //second way to find parent of deepest right node    }*/    for (int i = 0; i < travs.size(); i++) {        if (travs[i].first->data == key) {            keypos = travs[i].first;            break;        }    }       keypos->data = dprn->data;    if (travs[pdprni].first->right != NULL) {        travs[pdprni].first->right = NULL;    } else if (travs[pdprni].first->left != NULL) {        travs[pdprni].first->left = NULL;    }    free(dprn);    dprn = NULL;    return root;}
0
Protyush Nayak8 months ago
Protyush Nayak
void deleteNode( Node* root, Node * target){    queue<node*>q;    q.push(root);        while(q.empty() == false)    {        Node *temp = q.front();        q.pop();                if(temp->left)        {            if(temp->left == target)            {                delete(temp->left);                temp->left = NULL;                return;            }            else            {                q.push(temp->left);            }        }        if(temp->right)        {            if(temp->right == target)            {                delete(temp->right);                temp->right = NULL;                return;            }            else            {                q.push(temp->right);            }        }    }}struct Node* deletionBT(struct Node* root, int key){        if(root == NULL)    return NULL;        queue<node*>q;    q.push(root);    Node*mainnode = NULL;    Node*temp = NULL;        while(q.empty() == false)    {        temp = q.front();        q.pop();                if(temp->data == key)        {            mainnode = temp;        }        if(temp->left != NULL)        {            q.push(temp->left);        }        if(temp->right != NULL)        {            q.push(temp->right);        }    }        if(mainnode!= NULL)    {        int x = temp->data;        mainnode->data = x;        deleteNode(root,temp);    }        return root;    }
0
Puru Bhargava9 months ago
Puru Bhargava
Done it without using queue(Because there is possibility of member in queue to be greater the height of tree): Time Complexity: O(N)Auxiliary Space: O(Height of Tree) https://uploads.disquscdn.c...
0
Chandru9 months ago
Chandru
C++ Correct Answer:✅✅✅Note:There is a mistake in example 1 diagram,the root node 1 will be changed to the last node data 6
struct Node* deletionBT(struct Node* root, int key){    queue<node*>q;    q.push(root);    Node*temp;    Node*del,*last,*lastchild;    while(!q.empty())    {        int n=q.size();        for(int i=0;i<n;i++)        {            temp = q.front();            q.pop();                        if(temp->data == key)            del = temp;                        if(temp->left)            {                last = temp;                q.push(temp->left);            }            if(temp->right)            {                last = temp;                q.push(temp->right);            }        }    }    del->data = temp->data;    last->right==temp?last->right=NULL:last->left=NULL;    return root;}
0
Uchiha9 months ago
Uchiha
C++ Solution       0.1s
struct Node* deletionBT(struct Node* root, int key){    Node *last;    Node *lastParent;    Node *keyNode;    queue<node *=""> q;    if(!root){        return NULL;    }    q.push(root);        while(!q.empty()){        Node *cur = q.front();        int count = q.size();                while(count--){            Node * cur = q.front();            q.pop();            if(cur->data == key){                keyNode = cur;            }            if(cur->left){                lastParent = cur;                last = cur->left;                q.push(cur->left);            }            if(cur->right){                lastParent = cur;                last = cur->right;                q.push(cur->right);            }        }    }    keyNode->data = last->data;    if(lastParent->left == last){        lastParent->left = NULL;    }    else{        lastParent->right = NULL;    }    return root;}
0
BARSHA PAL10 months ago
BARSHA PAL
C++ SOLN...
struct Node* deletionBT(struct Node* root, int key){      if(!root){            return {};        }        queue<node*> q;        q.push(root);      struct Node* lastparent;      struct Node* last;      struct Node* change;        while(!q.empty()){
               struct Node*curr=q.front();               q.pop();               if(curr->data==key)               {                   change=curr;               }                if(curr->left)               {                   lastparent=curr;                   last=curr->left;                   q.push(curr->left);               }               if(curr->right)               {                   lastparent=curr;                   last=curr->right;                   q.push(curr->right);               }
        }        change->data=last->data;        if(lastparent->left==last){            lastparent->left=NULL;        }        else{            lastparent->right=NULL;        }        return root;
}
0
Ayush 01011 months ago
Ayush 010
Dont use delete keyword in this problem, when you are making the node to be deleted  equals to  NULL .
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.