-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBSTree.h
More file actions
145 lines (134 loc) · 3.7 KB
/
BSTree.h
File metadata and controls
145 lines (134 loc) · 3.7 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
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#ifndef BINARARY_SEARCH_TREE
#define BINARARY_SEARCH_TREE
#include <iostream>
#include "BinaryTree.h"
template<class T>
class BSTree : public BinaryTree<T>{ // 继承自二叉树
public:
BSTree()
{
this->root = NULL;
}
T* findMax()
{
if(this->root == NULL)
return NULL;
BTNode<T> *temp = this->root;
while (temp->rchild)
{
temp = temp->rchild;
}
return temp;
}
T* findMin()
{
if(this->root == NULL)
return NULL;
BTNode<T> *temp = this->root;
while (temp->Lchild)
{
temp = temp->Lchild;
}
return temp;
}
T* findX(T x)
{
if(this->root == NULL)
return NULL;
BTNode<T> *temp = this->root;
while (temp && temp->data != x)
{
if(temp->data > x)
temp = temp->lchild;
else
temp = temp->rchild;
}
return temp;
}
bool insert(T value)
{
try{
this->root = rinsert(value, this->root);
}
catch(int e){
if(e == -1)
cerr << "ERROR: Mermory Limit Exceeded!" << endl;
else if(e == -2)
cerr << "ERROR: Same Element Existing!" << endl;
return false; // 插入失败
}
return true;
}
bool remove(T value)
{
try{
this->root = rremove(value, this->root);
}
catch(int e){
return false; // 删除失败
}
return true;
}
// 无需定义析构函数 会调用父类析构函数释放内存
protected:
BTNode<T>* rfindMax(BTNode<T> *r)
{ // 递归实现 效率低
if(r == NULL)
return NULL;
if(r->rchild == NULL)
return r;
return rfindMax(r->rchild);
}
virtual BTNode<T>* rinsert(T x, BTNode<T> *p) // 加virtual动态联编
{
if(p == NULL)
{ // 找到插入位置 递归结束
p = new BTNode<T>(x);
if(p == NULL)
{
throw -1; // 内存不够
}
}
else if(p->data > x)
p->lchild = rinsert(x, p->lchild);
else if(p->data < x)
p->rchild = rinsert(x, p->rchild);
else
{
throw -2; // 元素重复
}
return p;
}
BTNode<T>* rremove(T x, BTNode<T> *p)
{
if(p == NULL)
{
throw -1; // 删除失败
}
else if(p->data == x)
{
if(p->lchild && p->rchild)
{ // 左右子树都非空
BTNode<T> *temp = rfindMax(p->lchild);
p->data = temp->data;
p->lchild = rremove(temp->data, p->lchild);
}
else
{
BTNode<T> *temp = p;
p = p->lchild ? p->lchild : p->rchild;
delete temp;
}
}
else if(p->data > x)
{
p->lchild = rremove(x, p->lchild);
}
else
{
p->rchild = rremove(x, p->rchild);
}
return p;
}
};
#endif