Delete a node from BST | Practice | GeeksforGeeks

Given a Binary Search Tree and a node value X. Delete the node with the given value X from the BST. If no node with value x exists, then do not make any change. 
Example 1:
Input:
      2
    /   \
   1     3
X = 12
Output: 1 2 3
Explanation: In the given input there
is no node with value 12 , so the tree
will remain same.

Example 2:
Input:
            1
             \
              2
                \
                 8 
               /    \
              5      11
            /  \    /  \
           4    7  9   12
X = 9
Output: 1 2 4 5 7 8 11 12
Explanation: In the given input tree after
deleting 9 will be
             1
              \
               2
                 \
                  8
                 /   \
                5     11
               /  \     \
              4    7     12
Your Task:
You don't need to read input or print anything. Your task is to complete the function deleteNode() which takes two arguments. The first being the root of the tree, and an integer 'X' denoting the node value to be deleted from the BST. Return the root of the BST after deleting the node with value X. Do not make any update if there's no node with value X present in the BST. 
Note: The generated output will be the inorder traversal of the modified tree.
 
Expected Time Complexity: O(Height of the BST).
Expected Auxiliary Space: O(Height of the BST).
 
Constraints:
1 <= N <= 105
 
0
utkarsh061 day ago
// Function to delete a node from BST.
Node *deleteNode(Node *root, int key)
{
     if(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 && !root->right) return NULL;        
                //No child condition
                if (!root->left || !root->right)
                    return root->left ? root->left : root->right;   
                //One child cond -> replace the node with it's child
					                                                
                //Two child condition   
                Node* temp = root->left;                       
                while(temp->right != NULL) temp = temp->right;    
            
                root->data = temp->data;                            
    
                root->left = deleteNode(root->left, temp->data); 	
            }
       }
        return root;
}   
0
amishasahu3282 weeks ago
Node *findLastRight(Node *root)
{
    if(root->right == NULL)
        return root;
    return findLastRight(root->right);
}
Node *helper(Node *root)
{
    if(root->left == NULL)
        return root->right;
    else if(root->right == NULL)
        return root->left;
        
    Node *rightChild = root->right;
    Node *lastRight = findLastRight(root->left);
    lastRight->right = rightChild;
    return root->left;
}
Node *deleteNode(Node *root, int X) {
    // your code goes here
    if(root == NULL) return NULL;
    if(root->data == X)
        return helper(root);
        
    Node *temp = root;
    while(root)
    {
        if(root->data > X)
        {
            if(root->left != NULL && root->left->data == X)
            {
                root->left = helper(root->left);
                break;
            }
            else
                root = root->left;
        }
        else
        {
            if(root->right != NULL && root->right->data == X)
            {
                root->right = helper(root->right);
                break;
            }
            else
                root = root->right;
    
        }
    }
        return temp;
}

0
jaydhurat3 weeks ago
class Tree {
   // Function to delete a node from BST.
   public static Node deleteNode(Node root, int k) {
       // code here.
       if(root==null)
       {
           return null;
       }
       if(root.data>k)
       {
          root.left= deleteNode(root.left,k);
       }
       else if(root.data<k)
       {
           root.right=deleteNode(root.right,k);
       }
       else
       {
           if(root.left==null)
           {
               return root.right;
           }
           else if(root.right==null)
           {
               return root.left;
           }
           root.data=min(root.right);
           root.right=deleteNode(root.right,root.data);
       }
       
       return root;
   }
   public static int min(Node root)
   {
       int minx=root.data;
       while(root.left!=null)
       {
           minx=root.left.data;
           root=root.left;
       }
       return minx;
   }
}
0
pushkarcoding101 month ago
python solution (0.3/1.0)
 
def deleteNode(root, X):   arr=inor(root,[])   if(X in arr):       arr.remove(X)   arr.sort()   ans=making(0,len(arr)-1,arr)   return ans   # code here.
def inor(root,a):   if(root==None):       return   else:       inor(root.left,a)       a.append(root.data)       inor(root.right,a)   return adef making(s,e,arr):   if(s>e):       return None   mid=(s+e)//2   root=Node(arr[mid])   root.left=making(s,mid-1,arr)   root.right=making(mid+1,e,arr)   return root
0
vallurisrinivas091 month ago
//BY VALLURI SRINIVAS
//JAVA
class Tree {
    // Function to delete a node from BST.
    
    public static Node helper(Node root){
        Node curr = root;
        curr = curr.right;
        while(curr!=null && curr.left!=null){
            curr = curr.left;
        }
        return curr;
    }
    
    public static Node deleteNode(Node root, int x) {
        // code here.
        if(root==null) return root;
        else if(root.data>x) root.left = deleteNode(root.left, x);
        else if(root.data<x) root.right = deleteNode(root.right, x);
        else{
            if(root.right==null) return root.left;
            else if(root.left==null) return root.right;
            else{
                Node succ = helper(root);
                root.data = succ.data;
                if(root.right.left==null) root.right = root.right.right;
                deleteNode(root.right, succ.data);
            }
        }
        return root;
    }
}
-1
nitianguddu8412081 month ago
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
#define MAX_HEIGHT 100000

// Tree Node
struct Node {
    int data;
    Node* left;
    Node* right;

    Node(int val) {
        data = val;
        left = right = NULL;
    }
};

struct Node* deleteNode(struct Node* root, int key);

// Function to Build Tree
Node* buildTree(string str) {
    // Corner Case
    if (str.length() == 0 || str[0] == 'N') return NULL;

    // Creating vector of strings from input
    // string after spliting by space
    vector<string> ip;

    istringstream iss(str);
    for (string str; iss >> str;) ip.push_back(str);

    // Create the root of the tree
    Node* root = new Node(stoi(ip[0]));

    // Push the root to the queue
    queue<Node*> queue;
    queue.push(root);

    // Starting from the second element
    int i = 1;
    while (!queue.empty() && i < ip.size()) {

        // Get and remove the front of the queue
        Node* currNode = queue.front();
        queue.pop();

        // Get the current node's value from the string
        string currVal = ip[i];

        // If the left child is not null
        if (currVal != "N") {

            // Create the left child for the current node
            currNode->left = new Node(stoi(currVal));

            // Push it to the queue
            queue.push(currNode->left);
        }

        // For the right child
        i++;
        if (i >= ip.size()) break;
        currVal = ip[i];

        // If the right child is not null
        if (currVal != "N") {

            // Create the right child for the current node
            currNode->right = new Node(stoi(currVal));

            // Push it to the queue
            queue.push(currNode->right);
        }
        i++;
    }

    return root;
}

void inorder(Node* root, vector<int>& v) {
    if (root == NULL) return;

    inorder(root->left, v);
    v.push_back(root->data);
    inorder(root->right, v);
}

int main() {

    int t;
    string tc;
    getline(cin, tc);
    t = stoi(tc);
    while (t--) {
        string s;
        getline(cin, s);
        Node* root1 = buildTree(s);
        getline(cin, s);
        int k = stoi(s);
        root1 = deleteNode(root1, k);
        vector<int> v;
        inorder(root1, v);
        for (auto i : v) cout << i << " ";
        cout << endl;
    }
    return 0;
}// } Driver Code Ends


// Function to delete a node from BST.
Node* minValue(Node* root){
    // if(root==NULL){
    //     return NULL;
    // }
    Node* temp=root;
    while(temp->left!=NULL){
        temp=temp->left;
    }
    return temp;
}
Node *deleteNode(Node *root, int X) {
    // your code goes here
    if(root==NULL){
        return root;
    }
    if(root->data==X){
        if(root->left==NULL && root->right==NULL){
            delete root;
            return NULL;
        }
        else if(root->left!=NULL && root->right==NULL){
            Node* temp=root->left;
            delete root;
            return temp;
        }
        else if(root->left==NULL && root->right!=NULL){
            Node* temp=root->right;
            delete root;
            return temp;
        }
        else if(root->left!=NULL && root->right!=NULL){
            int mini=minValue(root->right)->data;
            root->data=mini;
            root->right=deleteNode(root->right,mini);
            return root;
        }
    }
    else if(root->data>X){
        root->left=deleteNode(root->left,X);
        return root;
    }
    else{
        root->right=deleteNode(root->right,X);
        return root;
    }
    //return root;
}

+3
gaurabhkumarjha271020011 month ago
// concise c++ code
  int find (Node* root){
    
    while (root->left != nullptr)
        root=root->left;
        
        return root->data;
}
Node *deleteNode (Node *root, int x) {
    // your code goes here
    
     if (!root) return nullptr;
     
     if (root->data > x) 
   root->left= deleteNode(root->left, x);
     else if (root->data < x) 
   root->right= deleteNode(root->right, x);
     
     else{
         
         if (!root->left) return root->right;
         else if (!root->right) return root->left;
         
         else{
             
    root->data= find(root->right);
 root->right= deleteNode(root->right, root->data);
         }
     }
     
     return root;
}

0
paulakash9011 month ago
 Node* minVal(struct Node* root)
{
    Node* temp=root;
   while(temp->left!=NULL)
   {
       temp=temp->left;
   }
   return temp;
}
 Node* deleteNode( Node* root, int X){   //your code goes here   if(root==NULL)    return root;       if(root->data==X)    {       // 0 child       if(root->left==NULL && root->right==NULL)       {           delete root;           return NULL;       }       // 1 child       // left child        if(root->left!=NULL && root->right==NULL)        {            struct Node* temp=root->left;            delete root;            return temp;        }        // Right child         if(root->left==NULL && root->right!=NULL)         {            struct Node* temp=root->right;             delete root;            return temp;         }         // 2 child         if(root->left!=NULL && root->right!=NULL)         {            int mini=minVal(root->right)->data;            root->data=mini;            root->right=deleteNode(root->right,mini);            return root;         }   }   else if(root->data > X)   {       root->left=deleteNode(root->left,X);       return root;   }   else   {       root->right=deleteNode(root->right,X);       return root;   }   return root;}
0
smit1232 months ago
Node* findmin(Node* root){      Node* temp = root;   if(temp == NULL)   {       return NULL;   }   while(temp->left != NULL && temp != NULL)   {       temp = temp->left;   }   //temp = temp->right;   return temp;}Node *deleteNode(Node *root, int X) {   // your code goes here   if(root == NULL)   {       return root;   }   if(root->data == X)   {       // 0 child       if(root->left == NULL && root->right == NULL){                      delete root;           return NULL;       }       // 1 child of left       if(root->left != NULL && root->right == NULL)       {           Node* temp = root->left;           delete root;           return temp;       }
        //1 child of right       if(root->left == NULL && root->right != NULL)       {           Node* temp = root->right;           delete root;           return temp;       }       if(root->left != NULL && root->right != NULL)       {           int min = findmin(root->right)->data;           root->data = min;           root->right = deleteNode(root->right,min);           return root;       }   }   else if(root->data > X)   {       root->left = deleteNode(root->left,X);   }   else   {       root->right = deleteNode(root->right,X);   }   return root;}
0
gargnipungarg2 months ago
Understood the approach used for this, but could never remember the small tricks used, 3 months down the line.So tried keeping pointers to all nodes involved. Solution is cumbersome but performance and test cases all pass and can write this down again 1 year later as well.class Tree {   // Function to delete a node from BST.   public static Node deleteNode(Node root, int X) {       // code here.       if(root==null) return root;       travereAndDelete(root, root, null, "", X);       if(root.data==Integer.MIN_VALUE) return null;       else return root;   }      public static void travereAndDelete(Node root, Node current, Node parent, String child, int X){              if(current==null) return;       if(current.data < X) {           travereAndDelete(root, current.right, current, "right", X);       } else if(current.data > X) {           travereAndDelete(root, current.left, current, "left" , X);       }else{           if(current.left==null && current.right==null){               if(child =="left") parent.left=null;               else if(child =="right") parent.right=null;               else root.data=Integer.MIN_VALUE;           }else if(current.left==null){               if(child =="left") parent.left = current.right;               else if(child =="right") parent.right = current.right;               else {                   Node temp = root.right;                   root.right = null;                   root = temp;               }           }else if(current.right==null){               if(child =="left") parent.left = current.left;               else if(child =="right") parent.right = current.left;               else{                   Node temp = root.left;                   root.left = null;                   root = temp;               }           }else{               Node succParent = current;               String sideTemp = "right";               Node succ = current.right;               while(succ.left!=null){                   sideTemp = "left";                   succParent = succ;                   succ = succ.left;               }               if(sideTemp == "right") succParent.right=null;               else succParent.left=null;               current.data = succ.data;           }       }   }} 
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.