1127 ZigZagging on a Tree (30 分)
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
题目大意:
给出有n个结点的二叉树的中序和后序,输出其z型层序,以为着除了根结点以外,第一层从左到右层序,第二层从右到左。
思路:
由于不需要其他判定操作,那么就是简单的中序+后序转层序。然后构建好静态二叉树后,顺序遍历,将其放入ans中,遍历ans,发现结点层数是偶数时(定义根结点层数为0),就让相同层数的都reverse。由于reverse 函数的限制,就让ans存储编号,h 存储层数。
关于中序 + 后序转层序的模板在本博客内有,可以自行翻找。
参考代码:
#include<vector>
#include<cstdio>
#include<algorithm>
using namespace std;
vector<int> in, post;
struct node{
int v = -1, h;
};
node t[2000000];
vector<int> ans, h;
int n;
void level(int root, int st, int ed, int h, int idx){
if(st > ed) return;
t[idx].v = post[root]; t[idx].h = h;
int i = st;
while(i < ed && post[root] != in[i]) i++;
level(root - (ed - i) - 1, st, i - 1, h + 1, 2 * idx + 1);
level(root - 1, i + 1, ed, h + 1, 2 * idx + 2);
}
int main(){
scanf("%d", &n);
in.resize(n); post.resize(n);
for(int i = 0; i < n; ++i) scanf("%d", &in[i]);
for(int i = 0; i < n; ++i) scanf("%d", &post[i]);
level(n - 1, 0, n - 1, 0, 0);
for(int i = 0; i < 2000000; ++i)
if(t[i].v != -1) ans.push_back(t[i].v), h.push_back(t[i].h);
for(int i = 0; i < ans.size(); ++i)
if(h[i] % 2 == 0){
int j = i;
while(j < ans.size() && h[i] == h[j]) j++;
reverse(ans.begin() + i, ans.begin() + j);
i = j - 1;
}
for(int i = 0; i < ans.size(); ++i)
printf("%d%c", ans[i], i != n - 1? ' ': '\n');
return 0;
}