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
分析:1.通过中序和后序序列建树
2.建立队列queue递归每层节点,vector容器数组储存每层节点
3.根据当前层号的奇偶性分别从左往右、从右往左遍历输出
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<cmath>
#include<unordered_set>
//1009;
using namespace std;
typedef long long ll;
const int inf = 99999999;
int n;
int post[35], in[35];
struct Tree {
int key;
Tree* left;
Tree* right;
};
Tree* Create(int lin, int rin, int lpost, int rpost) {
if (lin>rin||lpost>rpost) return NULL;
int key = post[rpost];
Tree* root = new(Tree);
root->key = key;
root->left = root->right = NULL;
int index = -1;
for (int i = lin; i <= rin; i++) {
if (in[i] == key) {
index = i;
break;
}
}
int r = rin - index; //中序序列中右子树节点数
root->left = Create(lin, index-1, lpost, rpost-r-1);
root->right = Create(index+1, rin, rpost-r, rpost - 1);
return root;
}
vector<int> vt[35]; //保存每一层节点
queue<Tree*> q; //层序遍历
int Max = 0; //表示树的深度
void zigzigg(Tree* root,int depth) {
if (!root) return;
q.push(root);
Max = max(Max, depth);
vt[depth].push_back(root->key);
while (!q.empty()) {
Tree* node = q.front();
q.pop();
zigzigg(node->left, depth + 1);
zigzigg(node->right, depth + 1);
}
return;
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> in[i];
for (int i = 0; i < n; i++) cin >> post[i];
Tree* root = NULL;
root=Create(0,n-1,0,n-1);
zigzigg(root,0);
for (int i = 0; i <= Max; i++) {
//cout << vt[i].size() << endl;
if (i == 0) {
cout << vt[i][0];
}
else if (i % 2) {
for (int j = 0; j < vt[i].size(); j++) {
cout << " " << vt[i][j];
}
}
else {
for (int j = vt[i].size()-1; j >= 0; j--) {
cout << " " << vt[i][j];
}
}
}
}