-
Notifications
You must be signed in to change notification settings - Fork 62
/
Delete a node from BST
49 lines (41 loc) · 1.07 KB
/
Delete a node from BST
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
Node*deleteNode(Node *root, int x)
{
if(root==NULL)
return root;
else if(root->data>x)
{
root->left=deleteNode(root->left,x);
return root;
}
else if(root->data==x)
{
if(root->left==NULL && root->right==NULL)
{
delete root;
return NULL;
}
if(root->right!=NULL && root->left==NULL)
{
Node*temp=root->right;
delete root;
return temp;
}
if(root->left!=NULL && root->right==NULL)
{
Node*temp=root->left;
delete root;
return temp;
}
Node*temp=root->right;
while(temp->left!=NULL)
temp=temp->left;
root->data=temp->data;
root->right=deleteNode(root->right,temp->data);
return root;
}
else
{
root->right=deleteNode(root->right,x);
return root;
}
}