树的层次遍历(反转那一部分用一个栈保存,等这一层输入完成后就可将栈中保存的数据输出以达到反转的效果)
//
// main.cpp
// test6
//
// Created by Jacky Roth on 2019/2/28.
// Copyright © 2019 Jacky Roth. All rights reserved.
//
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn=35;
int in[maxn];
int post[maxn];
int n;
struct tree {
int data;
tree* lchild;
tree* rchild;
};
tree* creat_node(int x){
tree* root=new tree();
root->lchild=NULL;
root->rchild=NULL;
root->data=x;
return root;
}
tree* creat_tree(int inL,int inR,int postL,int postR){
if (inL>inR) {
return NULL;
}
int key=post[postR];
tree* root=creat_node(key);
int k=inL;
for (; k<=inR&&in[k]!=key; k++) {
}
int len=k-inL;
root->lchild=creat_tree(inL, k-1, postL, postL+len-1);
root->rchild=creat_tree(k+1, inR, postL+len, postR-1);
return root;
}
void level(tree* root){
queue<tree*>q;
q.push(root);
tree* top;
int now=1,nex=0;
int tag=-1;
stack<int>S;
while (!q.empty()) {
top=q.front();
q.pop();
now--;
if (tag==1) {
printf("%d",top->data);
if (--n) {
printf(" ");
}
}else{
S.push(top->data);
}
if (top->lchild) {
q.push(top->lchild);
nex++;
}
if (top->rchild) {
q.push(top->rchild);
nex++;
}
if (!now) {
now=nex;
nex=0;
if (tag==-1) {
while (!S.empty()) {
printf("%d",S.top());
if (--n) {
printf(" ");
}
S.pop();
}
}
tag*=-1;
}
}
printf("\n");
}
int main(int argc, const char * argv[]) {
scanf("%d",&n);
for (int i=0; i<n; i++) {
scanf("%d",&in[i]);
}
for (int i=0; i<n; i++) {
scanf("%d",&post[i]);
}
tree* root=creat_tree(0, n-1, 0, n-1);
level(root);
return 0;
}