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
难点是 叶子节点数为 30 2^30 大约是 10^9 最坏情况下(叶子成线性)数组创建10^9大小会超内存,所以用指针的方式建立树。
然后把层序遍历的结果保存 在输出就 ok 了
code
#pragma warning(disable:4996)
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class tree {
public:
int val;
tree* left = NULL, *right = NULL;
};
int inorder[35];
int postorder[35];
vector<int> vres[35];
void build(int q, int e, int l, int r, tree*& t);
void levelorder(tree* t);
int main() {
int n;
cin >> n;
for (int i = 0; i < n; ++i) cin >> inorder[i];
for (int i = 0; i < n; ++i) cin >> postorder[i];
tree* head = NULL;
build(0, n - 1, 0, n - 1, head);
levelorder(head);
bool f = 1;
for (int i = 1; i <= 35; ++i) {
if (vres[i].size() != 0) {
if (i % 2 == 0) {
for (int j = 0; j < vres[i].size(); ++j) {
if (f) f = 0;
else cout << ' ';
cout << vres[i][j];
}
}
else {
for (int j = vres[i].size() - 1; j >= 0; --j) {
if (f) f = 0;
else cout << ' ';
cout << vres[i][j];
}
}
}
}
system("pause");
return 0;
}
void levelorder(tree* t) {
if (t == NULL) return;
queue<pair<tree*,int>> q;
q.push(make_pair(t,1));
while (!q.empty()) {
pair<tree*,int> p = q.front();
q.pop();
vres[p.second].push_back(p.first->val);
if (p.first->left != NULL) q.push(make_pair(p.first->left, p.second + 1));
if (p.first->right != NULL) q.push(make_pair(p.first->right, p.second + 1));
}
}
void build(int q, int e, int l, int r, tree*& t) {
if (q > e) return;
int x = postorder[r];
t = new tree;
t->val = x;
if (q == e) return;
int pos = q;
for (; pos <= e; ++pos)
if (inorder[pos] == x) break;
build(q, pos - 1, l, l + (pos - q)-1,t->left);
build(pos + 1, e, l + (pos - q), r - 1, t->right);
}