Responsive Ads Here

Tuesday, 13 June 2017

Delete a node from BST

problem id:-http://practice.geeksforgeeks.org/problems/delete-a-node-from-bst/1


code:--



/* The structure of a BST Node is as follows:
struct Node {
  int data;
  Node * right, * left;
}; */
int min(Node *root,int &x)
    {
    if(root->left==NULL)
        {
        int temp=root->data;
        root->data=x;
        return temp;
        }
    return min(root->left,x);
    }
Node * deleteNode(Node *root,  int x)
{
if(root->data==x)
    {
    if(root->left==NULL && root->right==NULL)
        return NULL;
    else if(root->left!=NULL && root->right==NULL)
        return root->left;
    else if(root->left==NULL && root->right!=NULL)
        return root->right;
    else
        {
        root->data=min(root->right,x);
        root->right=deleteNode(root->right,x);
        return root;
        }
    }
else if(root->data >x && root->left!=NULL)
    {
    root->left=deleteNode(root->left,x);
    }
else if(root->data <x && root->right!=NULL)
    root->right=deleteNode(root->right,x);
return root;
}

No comments:

Post a Comment