Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences. And it is a simple standard routine to print the numbers in level-order. However, if you think the problem is too simple, then you are too naive. This time you are supposed to print the numbers in "zigzagging order" -- that is, starting from the root, print the numbers level-by-level, alternating between left to right and right to left. For example, for the following tree you must output: 1 11 5 8 17 12 20 15.
![zigzag.jpg zigzag.jpg](https://i-blog.csdnimg.cn/blog_migrate/94724de97baa373b179ecf9eb547afa8.jpeg)
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the inorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print the zigzagging sequence of the tree in a line. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
8
12 11 20 17 1 15 8 5
12 20 17 11 15 8 5 1
Sample Output:
1 11 5 8 17 12 20 15
#include <cstdio>
#include <cstring>
#include<iostream>
#include <vector>
#include<math.h>
#include<string>
#include<queue>
#include <algorithm>
#include<set>
#include<map>
using namespace std;
const int maxn= 1010; //最大顶点数
struct node{
int data,depth;
node *lchild,*rchild;
}*root;
int in[maxn],post[maxn],n;
vector<int> vect[maxn];
node * create(int in_l,int in_r,int post_l,int post_r){
if(in_l>in_r||post_l>post_r) return NULL; //most important;
node *root=new node; //most important;要重新定义;
root->data=post[post_r];
int k,num_left=0;
for(k=in_l;k<=in_r;k++,num_left++){
if(in[k]==post[post_r]) break;
}
root->lchild=create(in_l,k-1,post_l,post_l+num_left-1);
root->rchild=create(k+1,in_r,post_l+num_left,post_r-1);
return root;
}
int max_depth=-1;
void dfs(node *root,int depth){
if(root){
root->depth=depth;if(depth>max_depth) max_depth=depth;
vect[depth].push_back(root->data);
if(root->lchild) dfs(root->lchild,depth+1);
if(root->rchild) dfs(root->rchild,depth+1);
}
}
int main(){
cin>>n;
for(int i=0;i<n;i++) cin>>in[i];
for(int i=0;i<n;i++) cin>>post[i];
root=create(0,n-1,0,n-1);
dfs(root,1);
for(int i=1;i<=max_depth;i++){
if(i%2==0)
for(int j=0;j<vect[i].size();j++) {
if(j!=0) cout<<" ";
cout<<vect[i][j];
}
else for(int j=vect[i].size()-1;j>=0;j--) {
if(j!=vect[i].size()-1) cout<<" ";
cout<<vect[i][j];
}if(i!=max_depth) cout<<" ";
}
}