Source:
Description:
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.
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
Keys:
Attention:
- 开始方向弄反了-,-
Code:
/*
Data: 2019-05-31 21:17:07
Problem: PAT_A1127#ZigZagging on a Tree
AC: 33:50 题目大意:
假设树的键值为不同的正整数;
给出二叉树的中序和后序遍历,输出二叉树的“之字形”层次遍历; 基本思路:
建树,层次遍历,依次用队列和堆存储结点值,输出即可
*/ #include<cstdio>
#include<stack>
#include<queue>
using namespace std;
const int M=;
int in[M],post[M];
struct node
{
int data,layer;
node *lchild,*rchild;
}; node *Create(int postL, int postR, int inL, int inR)
{
if(postL > postR)
return NULL;
node *root = new node;
root->data = post[postR];
int k;
for(k=inL; k<=inR; k++)
if(in[k]==root->data)
break;
int numLeft = k-inL;
root->lchild = Create(postL, postL+numLeft-, inL,k-);
root->rchild = Create(postL+numLeft, postR-, k+,inR);
return root;
} void Travel(node *root)
{
queue<node*> q;
stack<node*> s;
root->layer=;
q.push(root);
while(!q.empty())
{
root = q.front();q.pop();
if(root->layer%==)
{
while(!s.empty())
{
printf(" %d", s.top()->data);
s.pop();
}
printf(" %d", root->data);
}
else{
if(root->layer==)
printf("%d", root->data);
else
s.push(root);
}
if(root->lchild){
root->lchild->layer=root->layer+;
q.push(root->lchild);
}
if(root->rchild){
root->rchild->layer=root->layer+;
q.push(root->rchild);
}
}
while(!s.empty())
{
printf(" %d", s.top()->data);
s.pop();
}
} int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("Test.txt", "r", stdin);
#endif int n;
scanf("%d", &n);
for(int i=; i<n; i++)
scanf("%d", &in[i]);
for(int i=; i<n; i++)
scanf("%d", &post[i]);
node *root = Create(,n-,,n-);
Travel(root); return ;
}