题目描述
给出一个数据序列,建立二叉排序树,并实现插入功能
对二叉排序树进行中序遍历,可以得到有序的数据序列
输入
第一行输入t,表示有t个数据序列
第二行输入n,表示首个序列包含n个数据
第三行输入n个数据,都是自然数且互不相同,数据之间用空格隔开
第四行输入m,表示要插入m个数据
从第五行起,输入m行,每行一个要插入的数据,都是自然数且和前面的数据不等
以此类推输入下一个示例
输出
第一行输出有序的数据序列,对二叉排序树进行中序遍历可以得到
从第二行起,输出插入第m个数据后的有序序列,输出m行
以此类推输出下一个示例的结果
输入样例1
1
6
22 33 55 66 11 44
3
77
50
10
输出样例1
11 22 33 44 55 66
11 22 33 44 55 66 77
11 22 33 44 50 55 66 77
10 11 22 33 44 50 55 66 77
示例代码
#include<iostream>
using namespace std;
class Binode
{
public:
int data;
Binode* lchild, * rchild;
Binode()
{
data = 0;
lchild = NULL;
rchild = NULL;
}
};
class Bitree
{
public:
Binode* root;
Bitree()
{
root = NULL;
}
Binode* getroot()
{
return root;
}
void createtree(int n)
{
int data,m;
while (n--) //创建
{
cin >> data;
insert(root, data);
}
midorder(root);
cout << endl;
cin >> m; //插入数据
while (m--)
{
cin >> data;
insert(root, data);
midorder(root);
cout << endl;
}
}
void insert(Binode*& p,int d) //引用指针参数,允许函数在执行过程中修改传入的指针变量 p 所指向的内存地址。
{
if (!p) //空就能插入
{
p = new Binode();
p->data = d;
}
else if(d<p->data)
{
insert(p->lchild, d);
}
else
{
insert(p->rchild, d);
}
}
void Insert()
{
int n, data;
cin >> n;
while (n--)
{
cin >> data;
insert(root, data);
midorder(root);
cout << endl;
}
}
void midorder(Binode* p) //中序遍历
{
if (p)
{
midorder(p->lchild);
cout << p->data << " ";
midorder(p->rchild);
}
}
};
int main()
{
int t,n;
cin >> t;
while (t--)
{
Bitree tree; //重要:树要写成局部变量,这样每一次都是不同的树
cin >> n;
tree.createtree(n);
}
return 0;
}
这题试了好几次,都是第一个样例过第二个不过,最后发现是把tree写在while外面了,正确解法应该写在while里面。
错误解法
int main()
{
int t,n,m;
cin >> t;
Bitree tree;
while (t--)
{
cin >> n;
tree.createtree(n);
}
// 在此处,tree 仍然在作用范围内
}
正确解法
int main()
{
int t,n;
cin >> t;
while (t--)
{
Bitree tree;
cin >> n;
tree.createtree(n);
}
}
在这种情况下,每次进入 while
循环时都会创建一个新的 tree
对象,并在循环结束时销毁。每次迭代都会使用一个独立的 tree
对象,它们之间不会保留任何状态或连接关系。