AVL Tree Deletion | Practice | GeeksforGeeks

Given a AVL tree and N values to be deleted from the tree. Write a function to delete a given value from the tree.
Example 1:

Tree = 
        4
      /   \
     2     6
    / \   / \  
   1   3 5   7

N = 4
Values to be deleted = {4,1,3,6}

Input: Value to be deleted = 4
Output:
        5    
      /   \
     2     6
    / \     \  
   1   3     7

Input: Value to be deleted = 1
Output:
        5    
      /   \
     2     6
      \     \  
       3     7

Input: Value to be deleted = 3
Output:
        5    
      /   \
     2     6
            \  
             7

Input: Value to be deleted = 6
Output:
        5    
      /   \
     2     7


Your Task:  
You dont need to read input or print anything. Complete the function delelteNode() which takes the root of the tree and the value of the node to be deleted as input parameters and returns the root of the modified tree.
Note: The tree will be checked after each deletion. 
If it violates the properties of balanced BST, an error message will be printed followed by the inorder traversal of the tree at that moment.
If instead all deletion are successful, inorder traversal of tree will be printed.
If every single node is deleted from tree, 'null' will be printed.
 
Expected Time Complexity: O(height of tree)
Expected Auxiliary Space: O(height of tree)

Constraints:
1 ≤ N ≤ 500
0
chhitizgoyal2 weeks ago
Java Solution.
class Sol{      Node root;   static int height(Node N)   {       if (N == null)           return 0;       return N.height;   }   static int max(int a, int b)   {       return (a > b) ? a : b;   }   static Node rightRotate(Node y)   {       Node x = y.left;       Node T2 = x.right;       // Perform rotation       x.right = y;       y.left = T2;       y.height = max(height(y.left), height(y.right)) + 1;       x.height = max(height(x.left), height(x.right)) + 1;       return x;   }   static Node leftRotate(Node x)   {       Node y = x.right;       Node T2 = y.left;       y.left = x;       x.right = T2;       x.height = max(height(x.left), height(x.right)) + 1;       y.height = max(height(y.left), height(y.right)) + 1;       return y;   }   static int getBalance(Node N)   {       if (N == null)           return 0;       return height(N.left) - height(N.right);   }       static Node minValueNode(Node node)   {       Node current = node;       while (current.left != null)       current = current.left;       return current;   }   public static Node deleteNode(Node root, int key)   {       if (root == null)           return root;       if (key < root.data)           root.left = deleteNode(root.left, key);       else if (key > root.data)           root.right = deleteNode(root.right, key);       else       {           if ((root.left == null) || (root.right == null))           {               Node temp = null;               if (temp == root.left)                   temp = root.right;               else                   temp = root.left;               if (temp == null)               {                   temp = root;                   root = null;               }               else                    root = temp;           }           else           {               Node temp = minValueNode(root.right);               root.data = temp.data;               root.right = deleteNode(root.right, temp.data);           }       }       if (root == null)           return root;       root.height = max(height(root.left), height(root.right)) + 1;       int balance = getBalance(root);       if (balance > 1 && getBalance(root.left) >= 0)           return rightRotate(root);       if (balance > 1 && getBalance(root.left) < 0)       {           root.left = leftRotate(root.left);           return rightRotate(root);       }       if (balance < -1 && getBalance(root.right) <= 0)           return leftRotate(root);       if (balance < -1 && getBalance(root.right) > 0)       {           root.right = rightRotate(root.right);           return leftRotate(root);       }       return root;   }}
+1
vinitkumawat1122 months ago
Easy C++ solution
 
int NodeHeight(Node* p)
{
    int hl=0, hr=0;
    hl = p&&p->left?p->left->height:0;
    hr = p&&p->right?p->right->height:0;
    return (hl>hr?hl+1:hr+1);
}

int BalanceFactor(Node* p)
{
    // hl-hr
    int hl=0, hr=0;
    hl = p&&p->left?p->left->height:0;
    hr = p&&p->right?p->right->height:0;
    
    return (hl-hr);
}

Node* LLRotate(Node* p)
{
    Node* pl = p->left;
    Node* plr = pl->right;
    
    pl->right = p;
    p->left = plr;
    
    p->height = NodeHeight(p);
    pl->height = NodeHeight(pl);
    
    return pl;
}

Node* LRRotate(Node* p)
{
    Node* pl = p->left;
    Node* plr = pl->right;
    
    pl->right = plr->left;
    p->left = plr->right;
    
    plr->left = pl;
    plr->right = p;
    
    p->height = NodeHeight(p);
    pl->height = NodeHeight(pl);
    plr->height = NodeHeight(plr);
    
    return plr;
}

Node* RRRotate(Node* p)
{
    Node* pr = p->right;
    Node* prl = pr->left;
    
    pr->left = p;
    p->right = prl;
    
    p->height = NodeHeight(p);
    pr->height = NodeHeight(pr);
    
    return pr;
}

Node* RLRotate(Node* p)
{
    Node* pr = p->right;
    Node* prl = pr->left;
    
    p->right = prl->left;
    pr->left = prl->right;
    
    prl->left = p;
    prl->right = pr;
    
    p->height = NodeHeight(p);
    pr->height = NodeHeight(pr);
    prl->height = NodeHeight(prl);
    
    return prl;
}

Node* InSuccessor(Node* p)
{
    while(p && p->left)
    {
        p=p->left;
    }
    return p;
}

Node* InPredecessor(Node* p)
{
    while(p && p->right)
    p=p->right;
    return p;
}


Node* deleteNode(Node* root, int data)
{
    if(root==NULL) return NULL;
    if(root->left==NULL && root->right==NULL)
    {
        if(data==root->data)
        {
            free(root);
            return NULL;
        }
    }
    
    if(data<root->data)
    root->left = deleteNode(root->left,data);
    else if(data>root->data)
    root->right = deleteNode(root->right,data);
    else
    {
        if(root->right!=NULL)
        {
            // successor
            Node* q = InSuccessor(root->right);
            root->data = q->data;
            root->right = deleteNode(root->right, q->data);
        }
        else
        {
            // Predecessor
            Node* q = InPredecessor(root->left);
            root->data = q->data;
            root->left = deleteNode(root->left,q->data);
        }
    }
    root->height = NodeHeight(root);
    if(BalanceFactor(root)==2 && BalanceFactor(root->left)==1)
    return LLRotate(root);
    else if(BalanceFactor(root)==2&&BalanceFactor(root->left)==-1)
    return LRRotate(root);
    else if(BalanceFactor(root)==2&&BalanceFactor(root->left)==0)
    return LLRotate(root);
    else if(BalanceFactor(root)==-2&&BalanceFactor(root->right)==1)
    return RLRotate(root);
    else if(BalanceFactor(root)==-2&&BalanceFactor(root->right)==-1)
    return RRRotate(root);
    else if(BalanceFactor(root)==-2&&BalanceFactor(root->right)==0)
    return RRRotate(root);
    
    return root;
}
0
arjun62613 months ago
can any one help me 
why it show run time error
int max(int a, int b){   if(a>b){       return a;   }   return b;}
int height(Node *root) {    if (root == NULL) {       return 0; }   return max(height(root->left),height(root->right))+1;}
 
 
Node *rightRotate(Node *y) {    Node *x = y->left;    Node *T2 = x->right;
      x->right = y;    y->left = T2;    y->height = height(y);   x->height =height(x);   return x; }
Node *leftRotate(Node *x) {    Node *y = x->right;    Node *T2 = y->left;    y->left = x;    x->right = T2;
      x->height = height(x);   y->height = height(y);
      return y; } //int bf(Node *N) {    if (N == NULL)        return 0;    return height(N->left) -           height(N->right); }
Node* insert(Node* node, int data) {    if (node == NULL)        return new Node(data);
   if (data < node->data)        node->left = insert(node->left, data);    else if (data > node->data)        node->right = insert(node->right, data);    else        return node;
      node->height = height(node);
      int b = bf(node);
      if (b> 1 && data < node->left->data)        return rightRotate(node);
   if (b < -1 && data > node->right->data)        return leftRotate(node);
   if (b > 1 && data > node->left->data)    {        node->left = leftRotate(node->left);        return rightRotate(node);    }
   if (b < -1 && data < node->right->data)    {        node->right = rightRotate(node->right);        return leftRotate(node);    }
      return node; }
Node * min(Node* node) {    Node* current = node;
      while (current->left != NULL)        current = current->left;
   return current; }
Node* deleteNode(Node* root, int data) {           if (root == NULL)        return root;
      if ( data < root->data)        root->left = deleteNode(root->left, data);
      else if( data > root->data )        root->right = deleteNode(root->right, data);    else   {               if( (root->left == NULL) ||           (root->right == NULL) )        {            Node *temp = root->left ?                         root->left :                         root->right;
                   if (temp == NULL)            {                temp = root;                root = NULL;            }            else // One child case            *root = *temp;                                     free(temp);        }        else       {                       Node* temp = min(root->right);
                     root->data = temp->data;
                       root->right = deleteNode(root->right,                                     temp->data);        }    }
   if (root == NULL)    return root;
      root->height = height(root);      int b = bf(root);
if (b> 1 && data < root->left->data)        return rightRotate(root);
   if (b < -1 && data > root->right->data)        return leftRotate(root);
   if (b > 1 && data > root->left->data)    {        root->left = leftRotate(root->left);        return rightRotate(root);    }
   if (b < -1 && data < root->right->data)    {        root->right = rightRotate(root->right);        return leftRotate(root);    }
 
   return root; } int max(int a, int b){   if(a>b){       return a;   }   return b;}
int height(Node *root) {    if (root == NULL) {       return 0; }   return max(height(root->left),height(root->right))+1;}
 
 
Node *rightRotate(Node *y) {    Node *x = y->left;    Node *T2 = x->right;
      x->right = y;    y->left = T2;    y->height = height(y);   x->height =height(x);   return x; }
Node *leftRotate(Node *x) {    Node *y = x->right;    Node *T2 = y->left;    y->left = x;    x->right = T2;
      x->height = height(x);   y->height = height(y);
      return y; } //int bf(Node *N) {    if (N == NULL)        return 0;    return height(N->left) -           height(N->right); }
Node* insert(Node* node, int data) {    if (node == NULL)        return new Node(data);
   if (data < node->data)        node->left = insert(node->left, data);    else if (data > node->data)        node->right = insert(node->right, data);    else        return node;
      node->height = height(node);
      int b = bf(node);
      if (b> 1 && data < node->left->data)        return rightRotate(node);
   if (b < -1 && data > node->right->data)        return leftRotate(node);
   if (b > 1 && data > node->left->data)    {        node->left = leftRotate(node->left);        return rightRotate(node);    }
   if (b < -1 && data < node->right->data)    {        node->right = rightRotate(node->right);        return leftRotate(node);    }
      return node; }
Node * min(Node* node) {    Node* current = node;
      while (current->left != NULL)        current = current->left;
   return current; }
Node* deleteNode(Node* root, int data) {           if (root == NULL)        return root;
      if ( data < root->data)        root->left = deleteNode(root->left, data);
      else if( data > root->data )        root->right = deleteNode(root->right, data);    else   {               if( (root->left == NULL) ||           (root->right == NULL) )        {            Node *temp = root->left ?                         root->left :                         root->right;
                   if (temp == NULL)            {                temp = root;                root = NULL;            }            else // One child case            *root = *temp;                                     free(temp);        }        else       {                       Node* temp = min(root->right);
                     root->data = temp->data;
                       root->right = deleteNode(root->right,                                     temp->data);        }    }
   if (root == NULL)    return root;
      root->height = height(root);      int b = bf(root);
if (b> 1 && data < root->left->data)        return rightRotate(root);
   if (b < -1 && data > root->right->data)        return leftRotate(root);
   if (b > 1 && data > root->left->data)    {        root->left = leftRotate(root->left);        return rightRotate(root);    }
   if (b < -1 && data < root->right->data)    {        root->right = rightRotate(root->right);        return leftRotate(root);    }
 
   return root; } 
0
gyanikug20cse4 months ago
Why i am getting wrong ans in this test case.
int height(Node *root){   if(!root) return 0;      return root->height;}
Node *insucc(Node *root){   while(root->left)   root=root->left;   return root;}
Node* rightRot(Node *r){   Node *rl=r->left;   Node *rlr=rl->right;      //Rotation   rl->right=r;   r->left=rlr;      return rl;}
Node* leftRot(Node *r){   Node *rr=r->right;   Node *rrl=rr->left;      //Rotation   rr->left=r;   r->right=rrl;      return rr;}
int getBalFac(Node *root){   if(!root) return 0;   return height(root->left)-height(root->right);}
Node* deleteNode(Node* root, int data){   //BST Deletion   if(!root) return NULL;      if(data<root->data)   root->left=deleteNode(root->left,data);   else if(data>root->data)   root->right=deleteNode(root->right,data);   else{              if(root->left==NULL||root->right==NULL)       {           Node *temp;           if(!root->left)           temp=root->right;           else           temp=root->left;                      if(temp==NULL)           {               temp=root;               root=NULL;           }           else           *root=*temp;                      free(temp);       }       else       {           Node *temp=insucc(root->right);           root->data=temp->data;           root->right=deleteNode(root->right,temp->data);       }   }   if(root==NULL)   return root;      root->height=1+max(height(root->left),height(root->right));      int bf=getBalFac(root);      if(bf==2&&getBalFac(root->left)>=0)   return rightRot(root);      if(bf==2&&getBalFac(root->left)==-1)   {       root->left=leftRot(root->left);       return rightRot(root);   }   if(bf==-2&&getBalFac(root->right)<=0)   return leftRot(root);      if(bf==-2&&getBalFac(root->right)==1)   {       root->right=rightRot(root->right);       return leftRot(root);   }      return root;      }
0
Y0U Cha*ngE9 months ago
Y0U Cha*ngE
int findheight(Node *root)    {        if(root==NULL)        return 0;        return  (1+ max(findheight(root->left),findheight(root->right)));    }    void updateheight(Node *root)    {        if(root==NULL)        return;        root->height= findheight(root);    }    int balancefactor(Node *root)    {        if(root==NULL)        return 0;        else          return (findheight(root->left) - findheight(root->right));    }    /*You are required to complete this method */    Node* LL(Node* root)    {        Node *l= root->left;        Node*lr= l->right;        l->right=root;        root->left=lr;        updateheight(root);        updateheight(l);        return l;    }    Node* RR(Node* root)    {        Node *r=root->right;        Node* rl=r->left;        r->left=root;        root->right=rl;        updateheight(root);        updateheight(r);        return r;
    }    Node* LR(Node *root)    {        root->left=RR(root->left);        return LL(root);    }    Node* RL(Node *root)    {        root->right=LL(root->right);        return RR(root);    }
Node* deleteNode(Node* root, int data){    if(root==NULL)    return root;    if(root->data >data)        root->left=deleteNode(root->left,data);    else if(root->data <data) root-="">right=deleteNode(root->right,data);    else if((root->data) == data)    {        if(!root->left && !root->right)          root=NULL;        else if(!root->left || !root->right)        {            Node *temp= ((root->left)?(root->left):(root->right));            root= temp;        }        else{            Node *temp=root->left;            while(temp->right!=NULL)             temp= temp->right;            root->data=temp->data;            root->left=deleteNode(root->left,temp->data);        }    }    updateheight(root);    int bl=balancefactor(root);    if(bl>1 && balancefactor(root->left)>=0)       root=LL(root);    if(bl>1 && balancefactor(root->left)<0)       root=LR(root);    if(bl<-1 && balancefactor(root->right)<=0)       root=RR(root);    if(bl<-1 && balancefactor(root->right)>0)       root=RL(root);
    return root;}
Possibly your code doesn't work correctly for multiple test-cases (TCs).
The first test case where your code failed:
Input:
80 51 95 29 66 89 99 6 40 N 71 N 94 98126 95 80 89 98 99 66 29 51 71 40 94
Its Correct output is:
null
And Your Code's output is:
Unbalanced BST, inorder traversal : 29 40 51 66 71...
0
Kunwar Sadanand
This comment was deleted.
0
Joya2 years ago
Joya
Get Clue with comment when you stuck at any point
+2
Pratiik Priyadarsan2 years ago
Pratiik Priyadarsan
Not an actual method to delete an element from an AVL tree. There will be rotations involved.But this is certainly a way to deal with the task at hand.
void inorder(vector<int>&v,Node*root,const int data){    if(root){        inorder(v,root->left,data);        if(root->data != data)            v.push_back(root->data);        inorder(v,root->right,data);    }}Node* buildTree(vector<int>&v,int s,int e){    if(s>e)        return NULL;    int mid = (s+e)/2;    Node* root = new Node(v[mid]);    root->left = buildTree(v,s,mid-1);    root->right = buildTree(v,mid+1,e);    return root;}Node* deleteNode(Node* root, int data){//add code here,    vector<int>v;    inorder(v,root,data);    return buildTree(v,0,v.size()-1);}
0
Kamal Meena2 years ago
Kamal Meena
Please Add Python  compiler And Add more Que on Avl Tree or  on red black tree
0
Animesh Srivastawa2 years ago
Animesh Srivastawa
can someone explain me what is wrong with my code ?void print(Node *root){  if(root == NULL)     return;   cout<<root->data<<"--->"<<root->height<<" ";   print(root->left);   print(root->right);}Node *inOrderSuc(Node *&parent, Node *root){    if(root == NULL)      return NULL;     if(root->left == NULL)      return root;       parent = root;       return inOrderSuc(parent, root->left);}int calculateHeight(Node *root){     int l = root->left ? root->left->height : 1;    int r = root->right ? root->right->height : 1;     return max(l, r);}Node* deleteNode(Node* root, int data){//add code here,   if(root == NULL)     return NULL;    if(root->data > data)     root->left = deleteNode(root->left, data);   else if(root->data < data)     root->right = deleteNode(root->right, data);   else if(root->data == data){       Node *tmp = root;       if(!root->left || !root->right){            if(!root->left && !root->right){               delete(root);               return NULL;           }            if(!root->left)             root = root->right;           else             root = root->left;         delete(tmp);       }       else{           Node *parent = root;           Node *inOrder = inOrderSuc(parent, root->right);           //Node *tmp = inOrder->right;           cout<<inorder->data<<" ";           if(parent == root)            parent->right = inOrder->right;           else            parent->left = inOrder->right;           inOrder->left = root->left; inOrder->right = root->right;           root = inOrder;           parent->height = calculateHeight(parent);           root->right = deleteNode(root->right, -1);           delete(tmp);       }   }    if(root != NULL){       int l = root->left ? root->left->height : 1;       int r = root->right ? root->right->height : 1;       int diff = abs(l - r);       if(diff > 1){           if(l > r){            //   print(root);            //   cout<<endl; int="" l1="root-">left->left ? root->left->left->height : 1;               int r1 = root->left->right ? root->left->right->height : 1;               int diff2 = l1 - r1;               if(diff2 < 0)                    root->left = leftRotate(root->left);               root = rightRotate(root);           }            else{               int l1 = root->right->left ? root->right->left->height : 1;               int r1 = root->right->right ? root->right->right->height : 1;               int diff2 = l1 - r1;               if(diff2 > 0)                  root->right = rightRotate(root->right);               root = leftRotate(root);           }       }     l = root->left ? root->left->height+1 : 1;     r = root->right ? root->right->height+1: 1;     root->height = max(l,r);     print(root);      cout<<endl; }="" return="" root;="" }="" <="" code="">
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.