-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path114-bst_remove.c
51 lines (50 loc) · 1.04 KB
/
114-bst_remove.c
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
50
51
#include "binary_trees.h"
/**
* bst_remove - a function that removes a node from a Binary Search Tree
* deletes the key and returns the new root
* @root: pointer to the root node of the tree to remove the value
* @value: value to remove in the tree
* Return: pointer to the new root node after removing the value
*/
bst_t *bst_remove(bst_t *root, int value)
{
bst_t *tmp, *succ, *succP;
if (root == NULL)
return (root);
if (root->n > value)
{
root->left = bst_remove(root->left, value);
return (root);
}
else if (root->n < value)
{
root->right = bst_remove(root->right, value);
return (root); }
if (root->left == NULL)
{
tmp = root->right;
free(root);
return (tmp); }
else if (root->right == NULL)
{
tmp = root->left;
free(root);
return (tmp);
}
else
{
succP = root;
succ = root->right;
while (succ->left != NULL)
{
succP = succ;
succ = succ->left;
}
if (succP != root)
succP->left = succ->right;
else
succP->right = succ->right;
root->n = succ->n;
free(succ);
return (root); }
}