Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

remove in bst

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

Node* inordersuccessor(Node* root){
    Node* curr=root;
    while(curr!=NULL && curr->left!=NULL){
        curr=curr->left;
    }
    return curr;
}

Node* remove(Node* root, int x){
    if(root==NULL) return root;
    else if(x<root->val){
        root->left=remove(root->left,x);
    }
    else if(x>root->val){
        root->right=remove(root->right,x);
    }
    else{
        if(root->left==NULL){
            Node* temp=root->right;
            delete(root);
            return temp;
        }
        else if(root->right==NULL){
            Node* temp=root->left;
            delete(root);
            return temp;
        }
        else{
            Node* ins=inordersuccessor(root->right);
            root->val=ins->val;
            root->right=remove(root->right,ins->val);
        }
        
    }
    return root;
}
Source by github.com #
 
PREVIOUS NEXT
Tagged: #remove #bst
ADD COMMENT
Topic
Name
3+5 =