Delete fron BST

Although my code is working fine for given testcase it gives wrong answer on submitting. please check the code https://ide.codingblocks.com/s/107983

Your code requires certain modifications, firstly, you have to simply check
if(root->data==data)
{
then
if (0 child)
else
if(1 left child)
else
if(1 right child)
else
{
2 children
}
}
else
if(root->data<data)
{
root->right=deleteInBST(root->right,data);
}
else
{
root->left=deleteInBST(root->left,data);
}
return root;
}

Plz modify your code as per these conditions only.

Done. https://ide.codingblocks.com/s/108000
but that makes no difference as my code earlier was exactly the same.

You are using a little wrong approach for building a tree by sorting the array, you have to use a normal approach to build the tree, since the tree that will be build using the sorted array will be different from the one build using the native approach,
node *insertInBST(node *root,int data)
{
if(root==NULL)
{
return new node(data);
}
if(data<=root->data)
{
root->left=insertInBST(root->left,data);
}
else
{
root->right=insertInBST(root->right,data);
}
return root;
}

Try using dis approach and then try to submit your code,
I have modified your code based on this approach only, you can refer that.

1 Like