-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path114-bst_remove.c
55 lines (49 loc) · 1.1 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
52
53
54
55
#include "binary_trees.h"
/**
* bst_remove - removes a node from a Binary Search Tree
* @root: a pointer to the root node of the tree where you will remove a node
* @value: the value to remove in the tree
* Return: a pointer to the new root node of the tree after removal
* NULL on failure
*/
bst_t *bst_remove(bst_t *root, int value)
{
bst_t *tmp = NULL;
if (!root)
return (NULL);
if (value < root->n)
root->left = bst_remove(root->left, value);
else if (value > root->n)
root->right = bst_remove(root->right, value);
else
{
if (!root->left)
{
tmp = root->right;
free(root);
return (tmp);
}
else if (!root->right)
{
tmp = root->left;
free(root);
return (tmp);
}
tmp = bst_min_val(root->right);
root->n = tmp->n;
root->right = bst_remove(root->right, tmp->n);
}
return (root);
}
/**
* bst_min_val - finds the smallest node from a Binary Search Tree
* @root: a pointer to the root node of the tree
* Return: a pointer to the smallest node
*/
bst_t *bst_min_val(bst_t *root)
{
bst_t *min = root;
while (min->left)
min = min->left;
return (min);
}