-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path114-bst_remove.c
More file actions
72 lines (69 loc) · 1.44 KB
/
114-bst_remove.c
File metadata and controls
72 lines (69 loc) · 1.44 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
63
64
65
66
67
68
69
70
71
72
#include <stdlib.h>
#include <stdio.h>
#include "binary_trees.h"
/**
* bst_remove - removes a node from a BST
*
* if the node has two children, it must be replaced with its first
* in-order successor
*
* @root: A pointer to the root node of the tree
* @value: The value to remove in the tree
*
* Return: A pointer to the new root node of the tree after removing
* the desired value
*/
bst_t *bst_remove(bst_t *root, int value)
{
bst_t *parent;
bst_t *successor;
bst_t *current;
current = root;
while (current != NULL && current->n != value)
{
parent = current;
if (current->n < value)
current = current->right;
else
current = current->left;
}
if (current == NULL)
return (root);
if (current->left == NULL)
{
if (parent == NULL)
root = current->right;
else if (parent->left == current)
parent->left = current->right;
else
parent->right = current->right;
free(current);
}
else if (current->right == NULL)
{
if (parent == NULL)
root = current->left;
else if (parent->left == current)
parent->left = current->left;
else
parent->right = current->left;
free(current);
}
else
{
successor = current->right;
parent = current;
while (successor->left != NULL)
{
parent = successor;
successor = successor->left;
}
current->n = successor->n;
if (parent->left == successor)
parent->left = successor->right;
else
parent->right = successor->right;
free(successor);
}
return (root);
}