输入样例:
3
1 2 4 5 3 6 7
4 2 5 1 6 3 7
输出样例:
1 2 3 4 5 6 7
输入样例:
3
4 2 5 1 6 3 7
4 5 2 6 7 3 1
输出样例:
1 2 3 4 5 6 7
这道题是学校里的大四学长亲自出的一道题目。我觉得很有意思,所以在这里和大家分享一下。
我认为这道题一共有两个难点:
1、通过中序以及前序或者后序还原整个二叉树,再进行层次输出。
2、如何判断给的两个数字序列是前中序还是中前序还是中后序还是后中序
第一个难点是属于基础知识,在我的另外一篇博客中有涉及到如何通过前序和中序序列还原二叉树并进行层次输出。当然啦,还有很多其他的大佬都有写过类似的更详细的文章,可以自行搜索。
第二个难点其实也很好解决,我们需要注意到题目中的一个小细节,那就是,题目给出的树是一棵满二叉树(满二叉树 满二叉树)重要的事情重复三遍!既然是满二叉树我们便能知道很多细节了。
- 结点总个数:2^h - 1 其中h就是满二叉树的高度
- 中序遍历中二叉树根节点的位置:n / 2 其中n是总结点个数
既然如此,我们就可以通过比对两串数据的头和中,尾和中,便可以知道两串数据到底给的是一个什么样的顺序。
下面给出实现代码以及测试点,以供参考。
#include <iostream>
#include <queue>
using namespace std;
struct node{
int v;
node *lchild, *rchild;
};
typedef node* tree;
//a数组, b数组分别存储输入的两串数据, s数组存储最后层序遍历过程中的数据(不直接在层序遍历中输出的原因是考虑到输出格式的控制,即输出的最后不含有空格)
int n,a[10000000],b[10000000];
int s[10000000], index = 0;
//中序 + 前序
tree creat(int inleft, int inright, int preleft, int preright, int in[], int pre[])
{
if(preleft > preright) return nullptr;
tree root = new node;
root->v = pre[preleft];
int k;
for(k = inleft; k <= inright; k++) {
if(in[k] == root->v)
break;
}
int numleft = k - inleft;
root->lchild = creat(inleft, inleft + k - 1, preleft + 1, preleft + numleft, in, pre);
root->rchild = creat(k + 1, inright, preleft + numleft + 1, preright, in, pre);
return root;
}
//中序 + 后序
tree creat1(int inleft, int inright, int postleft, int postright, int in[], int post[])
{
if(postleft > postright) return nullptr;
tree root = new node;
root->v = post[postright];
int k;
for(k = inleft; k <= inright; k++) {
if(in[k] == root->v)
break;
}
int numleft = k - inleft;
root->lchild = creat1(inleft, inleft + k - 1, postleft, postleft + numleft - 1, in, post);
root->rchild = creat1(k + 1, inright, postleft + numleft, postright - 1, in, post);
return root;
}
//层次
void BFS(tree root)
{
queue<tree> q;
q.push(root);
while(!q.empty()) {
tree temp = q.front();
q.pop();
s[index++] = temp->v;
if(temp->lchild != nullptr) q.push(temp->lchild);
if(temp->rchild != nullptr) q.push(temp->rchild);
}
}
int main()
{
int cnt = 1;
cin >> n;
for(int i = 0; i < n; i++)
cnt = cnt * 2;
cnt--;
for(int i = 0; i < cnt; i++)
scanf("%d",&a[i]);
for(int i = 0; i < cnt; i++)
scanf("%d",&b[i]);
tree root;
if(a[0] == b[cnt / 2])
root = creat(0, cnt - 1, 0, cnt - 1, b, a);
else if(b[0] == a[cnt / 2])
root = creat(0, cnt - 1, 0, cnt - 1, a, b);
else if(a[cnt - 1] == b[cnt / 2])
root = creat1(0, cnt - 1, 0, cnt - 1, b, a);
else if(b[cnt - 1] == a[cnt / 2])
root = creat1(0, cnt - 1, 0, cnt - 1, a, b);
BFS(root);
printf("%d",s[0]);
for(int i = 1; i < cnt; i++)
printf(" %d",s[i]);
return 0;
}