forked from m7robot/binary_trees
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path114-bst_remove.c
More file actions
63 lines (49 loc) · 1.17 KB
/
114-bst_remove.c
File metadata and controls
63 lines (49 loc) · 1.17 KB
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
56
57
58
59
60
61
62
#include "binary_trees.h"
/**
* bst_min_value_node - Finds the node with
* the smallest value in the BST.
* @node: Pointer to the root of the subtree to search.
* Return: Pointer to the node with the smallest value.
*/
bst_t *bst_min_value_node(bst_t *node)
{
bst_t *current = node;
while (current && current->left)
current = current->left;
return (current);
}
/**
* bst_remove - Removes a node from a Binary Search Tree.
* @root: Pointer to the root node of the tree.
* @value: The value to remove from the tree.
* Return: Pointer to the new root node
* after removing the desired value.
*/
bst_t *bst_remove(bst_t *root, int value)
{
if (root == NULL)
return (root);
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 == NULL)
{
bst_t *temp = root->right;
free(root);
return (temp);
}
else if (root->right == NULL)
{
bst_t *temp = root->left;
free(root);
return (temp);
}
bst_t *temp = bst_min_value_node(root->right);
root->n = temp->n;
root->right = bst_remove(root->right, temp->n);
}
return (root);
}