- 1. 二叉排序树
【问题描述】
请根据输入的数据创建一棵二叉排序树。然后执行相应操作。
1 删除某一值为x的结点
2 求指定结点y在二叉排序树中的层数
【输入形式】
结点数据,以0代表结束输入。
待删除的x,待求层数的y
【输出形式】
创建好的二叉排序树的拓展的前序遍历结果
删除后的二叉排序树的中序遍历结果
y所在的层数
【样例输入】
29 39 15 25 28 10 11 2 0
10
11
【样例输出】
29 15 10 2 # # 11 # # 25 # 28 # # 39 # #
2 11 15 25 28 29 39
4
【样例说明】
若待删除的结点包含左右子树,则以其左子树的最右结点代替它。
#include <iostream>
using namespace std;
int a[1000];
struct node
{
int data;
node *l;
node *r;
};
void insert(node *&t, int data)
{
if (t == NULL)
{
t = new node;
t->l = NULL;
t->r = NULL;
t->data = data;
}
else if (data > t->data)
{
insert(t->r, data);
}
else
insert(t->l, data);
}
void build(node *&t, int len)
{
t = NULL;
for (int i = 0; i < len; i++)
{
insert(t, a[i]);
}
}
void pre(node *t)
{
if (!t)
{
cout << "# ";
return;
}
cout << t->data << " ";
pre(t->l);
pre(t->r);
}
void midout(node *t)
{
if (!t)
{
return;
}
midout(t->l);
cout << t->data << " ";
midout(t->r);
}
void del(node *&t)
{
node *p;
if (t->l == NULL && t->r == NULL)
{
p = t;
t = NULL;
delete p;
}
else if (t->l == NULL)
{
p = t;
t = t->r;
delete p;
}
else if (t->r == NULL)
{
p = t;
t = t->l;
delete p;
}
else
{
node *parent = t;
node *pre = t->l;
while (pre->r)
{
parent = pre;
pre = pre->r;
}
t->data = pre->data;
if (t != parent)
{
parent->r = pre->l;
}
else
{
parent->l = pre->l;
}
delete pre;
}
}
void deleter(node *&t, int data)
{
if (data == t->data)
del(t);
else if (data < t->data)
deleter(t->l, data);
else
deleter(t->r, data);
}
int floor = 1;
void find(node *t, int data)
{
if (data == t->data)
{
cout << endl
<< floor;
return;
}
else if (data < t->data)
{
floor++;
find(t->l, data);
}
else
{
floor++;
find(t->r, data);
}
}
int main()
{
int i = 0;
while (1)
{
int data;
cin >> data;
if (data != 0)
{
a[i++] = data;
}
else
{
break;
}
}
int len = i;
node *t = NULL;
build(t, len);
int x, y;
cin >> x >> y;
pre(t);
deleter(t, x);
cout << endl;
midout(t);
find(t, y);
}