今天1024~~~~~~~~~~~
😜🙃😝
二叉平衡树的添加和查找操作
#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;
}
祝大家节日快乐!!!!!