-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path9_BST模板.cpp
97 lines (90 loc) · 1.96 KB
/
9_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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
struct Node
{
int data;
Node *lchild;
Node *rchild;
Node() { this->lchild = nullptr; this->rchild = nullptr; }
Node(int _data): data(_data) { this->lchild = nullptr; this->rchild = nullptr; }
};
Node* findMax(Node *root)
{
while (root->rchild != nullptr)
{
root = root->rchild;
}
return root;
}
Node* findMin(Node *root)
{
while (root->lchild != nullptr)
{
root = root->lchild;
}
return root;
}
// 插入节点
void ins(Node *&root, int x)
{
// 查找失败,也就是要插入的位置
if (root == nullptr)
{
root = new Node(x);
return;
}
if (root->data < x)
{
ins(root->rchild, x);
}
else if (root->data > x)
{
ins(root->lchild, x);
}
else
{
return;
}
}
// 删除节点
void del(Node *&root, int x)
{
// 没有找到要删除的节点
if (root == nullptr)
{
return;
}
// 找到这个要删除的节点
if (root->data == x)
{
// 无左右子树,叶子节点,直接删除
if (root->lchild == nullptr && root->rchild == nullptr)
{
delete root;
// 避免野指针
root = nullptr;
}
// 有左,查找左子树中的最大值,替换,递归
else if (root->lchild != nullptr)
{
Node *preNode = findMax(root->lchild);
root->data = preNode->data;
del(root->lchild, preNode->data);
}
// 有右无左,查找右子树中的最小值,替换,递归
else if (root->rchild != nullptr)
{
Node *nextNode = findMin(root->rchild);
root->data = nextNode->data;
del(root->rchild, nextNode->data);
}
}
// 向右子树递归
else if (root->data < x)
{
del(root->rchild, x);
}
// 向左子树递归
else if (root->data > x)
{
del(root->lchild, x);
}
}