-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path114-bst_remove.c
105 lines (102 loc) · 2.08 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include "binary_trees.h"
/**
* successor - get the next successor i mean the min node in the right subtree
* @node: tree to check
* Return: the min value of this tree
*/
int successor(bst_t *node)
{
int left = 0;
if (node == NULL)
{
return (0);
}
else
{
left = successor(node->left);
if (left == 0)
{
return (node->n);
}
return (left);
}
}
/**
* two_children - function that gets the next successor using the min
* value in the right subtree, and then replace the node value for
* this successor
* @root: node tat has two children
* Return: the value found
*/
int two_children(bst_t *root)
{
int new_value = 0;
new_value = successor(root->right);
root->n = new_value;
return (new_value);
}
/**
*remove_type - function that removes a node depending of its children
*@root: node to remove
*Return: 0 if it has no children or other value if it has
*/
int remove_type(bst_t *root)
{
if (!root->left && !root->right)
{
if (root->parent->right == root)
root->parent->right = NULL;
else
root->parent->left = NULL;
free(root);
return (0);
}
else if ((!root->left && root->right) || (!root->right && root->left))
{
if (!root->left)
{
if (root->parent->right == root)
root->parent->right = root->right;
else
root->parent->left = root->right;
root->right->parent = root->parent;
}
if (!root->right)
{
if (root->parent->right == root)
root->parent->right = root->left;
else
root->parent->left = root->left;
root->left->parent = root->parent;
}
free(root);
return (0);
}
else
return (two_children(root));
}
/**
* bst_remove - remove a node from a BST tree
* @root: root of the tree
* @value: node with this value to remove
* Return: the tree changed
*/
bst_t *bst_remove(bst_t *root, int value)
{
int type = 0;
if (root == NULL)
return (NULL);
if (value < root->n)
bst_remove(root->left, value);
else if (value > root->n)
bst_remove(root->right, value);
else if (value == root->n)
{
type = remove_type(root);
if (type != 0)
bst_remove(root->right, type);
}
else
return (NULL);
return (root);
}