给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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<iostream>
#include<queue>
using namespace std;
const int N = 35;
int n,in[N],post[N];
typedef struct BiTNode{
int val;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
BiTree build_Tree(int in[],int l1,int r1,int post[],int l2,int r2){
if(l1 > r1 || l2 > r2) return NULL;
BiTree root = new BiTNode;
root -> val = post[r2];
int tmp;
for(int i = l1;i <= r1;i++){
if(in[i] == post[r2]){
tmp = i;
break;
}
}
root -> lchild = build_Tree(in,l1,tmp -1,post,l2,l2 + tmp - l1 -1);
root -> rchild = build_Tree(in,tmp + 1,r1,post,l2 + tmp - l1,r2 - 1);
return root;
}
void levelOrder(BiTree root){
queue<BiTree> q;
if(root) q.push(root);
int flag = true;
while(q.size()){
auto tmp = q.front();
q.pop();
if(flag){
cout << tmp -> val;
flag = false;
}
else cout << " " << tmp -> val;
if(tmp -> lchild) q.push(tmp -> lchild);
if(tmp -> rchild) q.push(tmp -> rchild);
}
return;
}
int main(){
scanf("%d",&n);
for(int i = 0;i < n;i++) scanf("%d",&post[i]);
for(int i = 0;i < n;i++) scanf("%d",&in[i]);
BiTree root = build_Tree(in,0,n - 1,post,0,n - 1);
levelOrder(root);
cout << endl;
return 0;
}