-
Notifications
You must be signed in to change notification settings - Fork 0
/
handout_bst_remove.txt
111 lines (73 loc) · 3.1 KB
/
handout_bst_remove.txt
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
106
107
108
109
110
CSI 3334
Data structures
Exercises on removing nodes from a binary search tree
Exercise 1: removing a leaf node
You must do these steps:
- set the correct child pointer of the parent to NULL
- delete the node containing the item to remove
BSTNode<Base> *parent, *toRemove;
// ...
// Assume that toRemove points to the node to remove, and parent points
// to the parent of that node. Also, assume that the toRemove is a leaf
// node (has no children). You DON'T know which child of the parent
// toRemove is.
if (parent->left == toRemove) { // 1
Parent->left = NULL; // 2
} else {
Parent->right = NULL; // 3
}
delete toRemove; // 4
Exercise 2: removing a node with one child
You must do these steps:
- put the child of the node to remove in the place of the node to
remove
- delete the node containing the item to remove
BSTNode<Base> *parent, *toRemove;
// ...
// Assume that toRemove points to the node to remove, and parent points
// to the parent of that node. Also, assume that toRemove has one child.
// Note you DON'T know which child of the parent toRemove is, or which
// child toRemove has.
BSTNode<Base> *grandchild;
if (toRemove->left != NULL) {
grandchild = toRemove->left; // 1
toRemove->left = NULL // 2
} else {
Grandchild = toRemove->left; // 3
toRemove->right = NULL; // 4
}
if (parent->left == toRemove) {
Parent->left = grandchild; // 5
} else {
Parent->right = grandchild; // 6
}
delete toRemove; // 7
Exercise 3: removing a node with two children
Do the following steps:
- search for the leftmost node of the right subtree
- remove the leftmost node (keep track of its children)
- place the leftmost node in the same place as the node to remove
- remove and delete the node to remove
BSTNode<Base> *parent, *toRemove;
// ...
// Assume that toRemove has two children.
// Write the code that searches for the leftmost child of
// the right subtree.
BSTNode<Base> *leftMost = toRemove->right;
BSTNode<Base> *leftMostParent = toRemove;
if (leftMost->left != NULL) {
while (leftMost->left != NULL) {
leftMostParent = leftMost;
leftMost = leftMost->left;
}
leftMostParent->left = leftMost->right;
leftMost->right = toRemove->right;
}
leftMost->left = toRemove->left;
if (parent->left == toRemove) {
parent->left = leftMost;
} else {
parent->right = leftMost;
}
toRemove->left = toRemove->right = NULL;
delete toRemove;