题目描述:
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
思路:
分析题意:给定后序遍历和中序遍历,求层序遍历序列。
解题思路:后序遍历的顺序为左右根,中序遍历的顺序为根左右。这类题型的思路就是在后序遍历序列中根据中序遍历的次序找的左右子树的分界点,进行递归。由后序遍历的性质知道每个子树的根一定是后序遍历区间右端点,即编号最大的点。我们选择在中序遍历的序列上操作,可以知道根节点的左边是左子树,右边是右子树。结合后序遍历的性质——根节点的编号最大,找出根节点的下标和位置后,对左右子树递归就好。
代码:
#include<bits/stdc++.h>
using namespace std;
int a[55],b[55],c[55],d[55];
typedef struct emm{
int data;
struct emm *lchild,*rchild;
}*lt,rt;
lt build(int l,int r){
if(l>r) return NULL;
//zhao chu left
int pos,po = 0;
for(int i = l;i <= r; ++i){
if(d[b[i]] > po){
po = d[b[i]];
pos = i;
}
}
lt bt = new rt;
bt->data = b[pos];
bt->lchild = build(l,pos-1);
bt->rchild = build(pos+1,r);
return bt;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for(int i = 1;i <= n; ++i) cin >>a[i],d[a[i]] = i;
for(int i = 1;i <= n; ++i) cin >>b[i],c[b[i]] = i;
lt bt = build(1,n);
queue<lt>q;
q.push(bt);
int flag= 0;
while(!q.empty()){
lt tmp = q.front();q.pop();
if(flag == 0)cout << tmp->data;
else cout << " "<<tmp->data;
flag = 1;
if(tmp->lchild) q.push(tmp->lchild);
if(tmp->rchild) q.push(tmp->rchild);
}
return 0;
}