随机产生数据,显示一个二叉树
#include <iostream>
#include <vector>
#include <time.h>
using namespace std;
#define MAX_SIZE 1000
typedef struct Node {
int key;
int l, r; //左右指针
} Node;
Node tree0[MAX_SIZE] = {{0, 0, 1}}; //结构体类型数组
int cnt;
void add(int key, int &root = tree0[0].r) { //将一个整型键值key添加到一个二叉搜索树中,并且将根节点的地址存储在root中。如果没有传入root参数,则默认使用tree0[0].r作为根节点的地址。
if (root == 0)
{
root = ++cnt; //cnt++ && root=cnt
tree0[cnt] = {key, 0, 0};
}
else
{
if (key < tree0[root].key)
add(key, tree0[root].l);
else
if (key > tree0[root].key)
add(key, tree0[root].r);
}
}
在代码后注释,运行是否有错误
void del(int key, int &root = tree0[0].r) {
if (root == 0)
return;
auto &p = tree0[root].r;
if (key < p.key)
del(key, p.l);
else if (key > p.key)
del(key, p.r);
else {
if (p.l == 0 && p.r == 0)
root = 0;
else if (p.l == 0 && p.r != 0)
root = p.r;
else if (p.l != 0 && p.r == 0)
root = p.l;
else if (tree0[p.r].l == 0) { //后继是右子树的根
tree0[p.r].l = p.l;
root = p.r;
} else {
int last = root;
root = p.r;
while (tree0[root].l != 0) { //找右子树的最小值,维护父指针last
last = root;
root = tree0[root].l;
}
tree0[last].l = tree0[root].r;
tree0[root].l = p.l;
tree0[root].r = p.r;
}
}
}
//
void show(int root = 1, vector<string> pre = vector<string>(0));
int main() {
system("cls");
srand(time(0));
for (int i = 1; i <= 20; ++i)
add(rand() % 100);
show();
int ch = 1;
do {
int temp;
puts("请输出操作码:");
puts("1:打印");
puts("2:删除");
puts("0:退出");
cin >> ch;
if (ch == 1)
show();
else if (ch == 2) {
cin >> temp;
del(temp);
}
} while (ch);
}
inline void trans(vector<string> &x, string before, string after) {
for (auto &p : x)
if (p == before) {
p = after;
break;
}
}
void show(int root, vector<string> pre) {
auto &p = tree0[root];
if (p.key != 0) {
vector<string> temp(pre);
trans(temp, "┌──", " ");
trans(temp, "└──", "│ ");
temp.push_back("┌──");
show(p.l, temp);
}
for (auto &i : pre)
cout << i;
if (p.key == 0)
cout << "null" << endl;
else
cout << p.key << endl;
if (p.key != 0) {
vector<string> temp(pre);
trans(temp, "┌──", "│ ");
trans(temp, "└──", " ");
temp.push_back("└──");
show(p.r, temp);
}
}