题目
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结尾无空行
思路
中序加后序建树,z字形输出(bfs存储到分层,按奇偶层正逆序输出) 比较常见了
代码
#include <bits/stdc++.h>
using namespace std;
const int maxn = 32;
int n;
int inorder[maxn];
int postorder[maxn];
vector<int> za[maxn];
int maxhei = 0;
struct node {
int data;
node* lchild;
node* rchild;
node(int d): data(d), lchild(NULL), rchild(NULL) {
}
};
void dfs(node* root, int height) {
if (root == NULL) return ;
if (height > maxhei) maxhei = height;
za[height].push_back(root->data);
dfs(root->lchild, height + 1);
dfs(root->rchild, height + 1);
}
node* create(int ina, int inb, int posta, int postb) {
if (ina > inb) return NULL;
int ro = postorder[postb];
node* root = new node(ro);
int i;
for (i = ina; i <= inb; i++) {
if (inorder[i] == ro) break;
}
int numleft = i - ina;
root->lchild = create(ina, ina + numleft - 1, posta, posta + numleft - 1);
root->rchild = create(ina + numleft + 1, inb, posta + numleft, postb - 1);
return root;
}
int main() {
cin>>n;
for (int i = 0; i < n; i++) {
cin>>inorder[i];
}
for (int i = 0; i < n; i++) {
cin>>postorder[i];
}
node* root = NULL;
root = create(0, n - 1, 0, n - 1);
dfs(root, 0);
cout<<root->data;
for (int i = 1; i <= maxhei; i++) {
if (i % 2 == 1) {
for (int j = 0; j < za[i].size(); j++) {
cout<<" "<<za[i][j];
}
} else {
for (int j = za[i].size() - 1; j >= 0 ; j--) {
cout<<" "<<za[i][j];
}
}
}
}