-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbst.cpp
82 lines (73 loc) · 1.67 KB
/
bst.cpp
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
#include <iostream>
using namespace std;
class BST {
int data;
BST *left, *right;
public:
BST();
BST(int);
BST* Insert(BST*, int);
void Delete(BST*&, int);
void Inorder(BST*);
};
BST::BST() : data(0), left(nullptr), right(nullptr) {}
BST::BST(int value) : BST() {
data = value;
}
BST* BST::Insert(BST* root, int value) {
if (!root) {
return new BST(value);
}
if (value > root->data) {
root->right = Insert(root->right, value);
} else {
root->left = Insert(root->left, value);
}
return root;
}
void BST::Delete(BST*& root, int value) {
if (!root) {
return;
}
if (root->data == value) {
if (!root->left && !root->right) {
delete root;
root = nullptr;
} else if (!root->left || !root->right) {
BST* child = root->left ? root->left : root->right;
BST* curr = root;
root = child;
delete curr;
curr = nullptr;
} else {
BST* inorderSuccessor = root->right;
while (inorderSuccessor->left) {
inorderSuccessor = inorderSuccessor->left;
}
root->data = inorderSuccessor->data;
Delete(root->right, inorderSuccessor->data);
}
} else if (value > root->data) {
Delete(root->right, value);
} else {
Delete(root->left, value);
}
}
void BST::Inorder(BST* root) {
if (!root) {
return;
}
Inorder(root->left);
cout << root->data << " ";
Inorder(root->right);
}
int main() {
BST bst, *root = nullptr;
int keys[] = { 4, 2, 7, 5, 6, 1, 3 };
for (int key : keys) {
root = bst.Insert(root, key);
}
bst.Delete(root, 4);
bst.Inorder(root);
return 0;
}