BST

binary search tree

BST是二叉搜索树,满足中序遍历是一个有序的序列,他是最最基础的二叉树,他不一定平衡,

BST insert

插入的时候,在树上递归插入,比当前节点大就向右边走,否则向左走

查找的时候,同上

BST erase

删除的时候,相对复杂,如果只有一个儿子,很简单,但是当他有两个儿子的时候,我们可以选择将一个儿子顶替自己,另外一个儿子去找前驱或后继即可。

BST code

我们使用内存池来维护整个数据结构
BST代码
treeview raw
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
#pragma once
#include "../memery_management/memery_pool.h"
#include "search_tree.h"

namespace data_structure {
template <class T>
class binary_search_tree : public search_tree<T> {
struct node {
node *ls, *rs;
T key;
};
memery_pool<node> pool;
node* root = nullptr;
void copy_self(node*& rt, node* cp) {
if (cp == nullptr) return;
rt = pool.get();
rt->key = cp->key;
copy_self(rt->ls, cp->ls);
copy_self(rt->rs, cp->rs);
}
void delete_self(node* rt) {
if (rt == nullptr) return;
delete_self(rt->ls);
delete_self(rt->rs);
pool.erase(rt);
}
node* newnode(const T& w) {
node* res = pool.get();
res->ls = res->rs = nullptr;
res->key = w;
return res;
}
void insert(node*& rt, const T& w) {
if (rt == nullptr)
rt = newnode(w);
else if (w < rt->key)
insert(rt->ls, w);
else if (rt->key < w)
insert(rt->rs, w);
}
node*& search(node*& rt, const T& w) {
if (rt == nullptr)
return rt;
else if (w < rt->key)
return search(rt->ls, w);
else if (rt->key < w)
return search(rt->rs, w);
else
return rt;
}
void erase(node*& rt, const T& w) {
if (rt == nullptr) {
return;
} else if (w < rt->key) {
erase(rt->ls, w);
} else if (rt->key < w) {
erase(rt->rs, w);
} else {
node* cur = rt;
if (rt->ls == nullptr) {
rt = rt->rs;
pool.erase(cur);
} else if (rt->rs == nullptr) {
rt = rt->ls;
pool.erase(cur);
} else {
cur = cur->rs;
while (cur->ls != nullptr) cur = cur->ls;
rt->key = cur->key;
erase(rt->rs, cur->key);
}
}
}
void preorder(node*& rt, void (*f)(const T&)) {
if (rt == nullptr) return;
f(rt->key);
preorder(rt->ls, f);
preorder(rt->rs, f);
}
void midorder(node*& rt, void (*f)(const T&)) {
if (rt == nullptr) return;
midorder(rt->ls, f);
f(rt->key);
midorder(rt->rs, f);
}

public:
// 构造函数和析构函数
binary_search_tree() { root = nullptr; }
binary_search_tree(const binary_search_tree<T>& rhs) {
copy_self(root, rhs.root);
}
binary_search_tree<T> operator=(const binary_search_tree<T>& rhs) {
delete_self(root);
copy_self(root, rhs.root);
return *this;
}
~binary_search_tree() { delete_self(root); }

//普通操作
void insert(const T& w) { insert(root, w); }
node*& search(const T& w) { return search(root, w); }
void erase(const T& w) { erase(root, w); }
void preorder(void (*f)(const T&)) { preorder(root, f); }
void midorder(void (*f)(const T&)) { midorder(root, f); }
};
} // namespace data_structure