二叉查找树精华修改版实现
实现功能如下
- 置空树功能
- 查找功能
- 查找最小值功能
- 查找最大值功能
- 插入功能
- 删除功能
- 层序遍历功能(BFS)
- 等等。。。。可以自己进行添加
代码实现如下
#include <iostream>
#include <string>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
struct BinSeaTree;
struct ElementType;
typedef struct BinSeaTree* BST;
int pd = 0;//非常重要!添加节点时,判断该树是否为空树
struct ElementType {
int data;
};
struct BinSeaTree {
ElementType key;
BST Left;
BST Right;
};
BST Init(BST& b) {
b = new BinSeaTree();
b->Left = NULL;
b->Right = NULL;
return b;
}
void MakeEmpty(BST b) {
if (b) {
MakeEmpty(b->Left);
MakeEmpty(b->Right);
delete b;
}
}
BST Find(ElementType x , BST b) {
if (!b) return NULL;
if (x.data == b->key.data) return b;
else if (x.data < b->key.data) Find(x, b->Left);
else if (x.data > b->key.data) Find(x, b->Right);
}
BST FindMin(BST b) {
if (!b->Left) return b;
else FindMin(b->Left);
}
BST FindMax(BST b) {
if (!b->Right) return b;
else FindMax(b->Right);
}
BST Insert(ElementType x, BST b) {
if (pd == 0) {
pd = 1;
b->key = x;
return NULL;
}
if (!b) {
BST newNode = new BinSeaTree();
newNode->key = x;
newNode->Left = NULL;
newNode->Right = NULL;
b = newNode;
}
else {
if (x.data < b->key.data) b->Left = Insert(x, b->Left);
else if (x.data > b->key.data) b->Right = Insert(x, b->Right);
}
return b;
}
BST Delete(ElementType x, BST b) {
if (x.data < b->key.data) b->Left = Delete(x, b->Left);
else if (x.data > b->key.data) b->Right = Delete(x, b->Right);
else {
if (b->Left && b->Right) {
BST temp;
temp = FindMin(b->Right);
b->key = temp->key;
b->Right = Delete(temp->key, b->Right);
}
else {
BST temp;
temp = b;
if (b->Left == NULL) b = b->Right;
else if (b->Right == NULL) b = b->Left;
delete temp;
}
}
return b;
}
void Display(BST b) {
queue<BST> que;
BST temp = new BinSeaTree();
temp = b;
que.push(temp);
while (temp) {
if (temp->Left) que.push(temp->Left);
if (temp->Right) que.push(temp->Right);
cout << que.front()->key.data << endl;
que.pop();
if (que.empty()) return;
temp = que.front();
}
}
int main() {
BST b;
b = Init(b);
ElementType a, s, d, f, g, h, j, k, l;
a.data = 10;
s.data = 7;
d.data = 15;
f.data = 8;
g.data = 4;
h.data = 9;
j.data = 14;
k.data = 20;
l.data = 17;
Insert(a, b);
Insert(s, b);
Insert(d, b);
Insert(f, b);
Insert(g, b);
Insert(h, b);
Insert(j, b);
Insert(k, b);
Insert(l, b);
Display(b);
cout << endl;
//BST e=FindMin(b->Right);
//cout << e->key.data << endl;
//e = FindMax(b->Right);
//cout << e->key.data << endl;
//Delete(l, b);
//Display(b);
//cout << endl;
return 0;
}
欢迎大家审阅😄