给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
找到根节点在中序序列的位置后(设为idne),则左子树的节点数量为numL = inde - l。
而中序序列被inde分成左右两半。
则让左子树再进行create(L,L-numL-1,l,inde-1)
右子树(L-numL,R-1,inde+1,r)
#include <bits/stdc++.h>
#define rep(i, a, b) for(int i = a; i <= b; ++ i)
#define per(i, a, b) for(int i = a; i >= b; -- i)
using namespace std;
int a[40],b[40];
struct node{
int value;
struct node *l,*r;
};
node *root;
int n;
node *creat(int L,int R,int l,int r){
if(L > R || l > r) return NULL;
node *u = new node; u->l=u->r = NULL;
u->value = a[R];
int inde;
rep(i,l,r){
if(a[R] == b[i]){
inde = i;
break;
}
}
int numL = inde - l;
u->l = creat(L,L+numL-1,l,inde-1);
u->r = creat(L+numL,R-1,inde+1,r);
return u;
}
int main(){
cin >> n;
rep(i,1,n) cin >> a[i];
rep(i,1,n) cin >> b[i];
root = creat(1,n,1,n);
vector<int> ans;
queue<node*> q; q.push(root);
while(q.size()){
node* t = q.front();q.pop();
ans.push_back(t->value);
if(t->l != NULL) q.push(t->l);
if(t->r != NULL) q.push(t->r);
}
cout << ans[0];
rep(i,1,ans.size()-1) cout << " " << ans[i];
return 0;
}