# 二叉平衡树的添加和查找操作

4 篇文章 0 订阅

😜🙃😝

#include <iostream>
#include <algorithm>
using namespace std;
int pd = 0;//非常重要，判断一棵树是不是空树

struct treeNode;
typedef struct treeNode* BST;
struct ElementType;

struct ElementType {
int key;
};

struct treeNode {
ElementType data;
treeNode* leftNode;
treeNode* rightNode;
};

BST Init(BST& b) {
treeNode* temp = new treeNode();
if (temp == NULL) return NULL;
temp->leftNode = NULL;
temp->rightNode = NULL;
b = temp;
return b;
}

void Display(BST b, int i) {//相当于前序遍历   如何进行层序遍历？
cout << "位置: " << i << "，元素为：" << b->data.key << endl;
if (b->leftNode) Display(b->leftNode, i * 2);
if (b->rightNode) Display(b->rightNode, i * 2 + 1);
}

bool Insert(const ElementType x, BST b) {
if (pd == 0) {
b->data = x;
pd = 1;
return true;
}
treeNode* temp = new treeNode();
temp = b;
//需要用一个指针指向这个节点的父节点
treeNode* father=new treeNode();
father = temp;
while (temp) {
father = temp;
if (temp->data.key == x.key) return false;
else if (temp->data.key > x.key) temp = temp->leftNode;
else temp = temp->rightNode;
}
treeNode* son = new treeNode();
son->data = x;
son->leftNode = NULL;
son->rightNode = NULL;
if (father->data.key > son->data.key) father->leftNode = son;
else father->rightNode = son;
return true;
}

treeNode* SearchRecursion(const ElementType x, treeNode* b) {
//if (b) {
//	if (x.key == b->data.key) return b;
//	else if (x.key < b->data.key) SearchRecursion(x, b->leftNode);
//	else SearchRecursion(x, b->rightNode);
//}
//return NULL;/that why? this has an error message.
if (!b) return NULL;
if (x.key == b->data.key) return b;
else if (x.key < b->data.key) SearchRecursion(x, b->leftNode);
else SearchRecursion(x, b->rightNode);

}

treeNode* SearchIteration(const ElementType x, const BST b) {
treeNode* temp = new treeNode();
temp = b;
while (b) {
if (x.key == temp->data.key) return temp;
else if (x.key < temp->data.key) temp = temp->leftNode;
else temp = temp->rightNode;
}
return NULL;
}

int main() {
BST b;
b = Init(b);
ElementType q, w, e, r, t, y, u, i, o, p, s;
q.key = 5;
w.key = 10;
e.key = 4;
r.key = 2;
t.key = 7;
y.key = 9;
u.key = 1;
i.key = 3;
o.key = 12;
p.key = 0;
s.key = 6;
Insert(q, b);
Insert(w, b);
Insert(e, b);
Insert(r, b);
Insert(t, b);
Insert(y, b);
Insert(u, b);
Insert(i, b);
Insert(o, b);
Insert(p, b);
Insert(s, b);

Display(b, 1);

treeNode* a1 = new treeNode();
a1 = SearchIteration(p, b);
cout << a1->data.key << endl;

a1 = SearchRecursion(u, b);
cout << a1->data.key << endl;

return 0;
}


• 1
点赞
• 0
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

09-18 1万+
04-04 1983

11-17 8102
11-21 594
11-26 2058
06-25 4475
09-05 7359
01-03 268
02-14 772
04-21 152
06-12 1383
09-07 780

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。