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
题意
先根据给出的中序遍历和后序遍历建树,在用Z字形层序遍历输出结果。
PS:一道题做1.5h也是绝了,期间还要看算法笔记,没几天就要考了,焦虑ing……
代码
#include <iostream>
#include <queue>
#include <vector>
#include <cmath>
using namespace std;
struct node {
int data,layer;
node *left,*right;
};
int post[31],in[31],maxlayer;
vector<int> v[31];
node* create(int ps,int pe,int is,int ie) { //后序、中序确定一棵二叉树
if(ps>pe) return NULL;
node* root=new node;
root->data = post[pe];
int k;
for(k=is; k<=ie; k++) {
if(in[k]==post[pe]) {
break;
}
}
int numleft=k-is; //左子树个数
//返回左子树的根结点地址,赋值给root的左指针
root->left=create(ps,ps+numleft-1,is,k-1);
//返回右子树的根结点地址,赋值给root的右指针
root->right=create(ps+numleft,pe-1,k+1,ie);
return root; //返回根节点地址
}
void zOrder(node* root) { //Z字形层序遍历
queue<node*> q;
root->layer=1;
v[root->layer].push_back(root->data);
q.push(root);
while(!q.empty()) {
node* now=q.front();
q.pop();
maxlayer=max(now->layer,maxlayer);
if(now->left!=NULL) {
now->left->layer=now->layer+1;
v[now->left->layer].push_back(now->left->data);
q.push(now->left);
}
if(now->right!=NULL) {
now->right->layer=now->layer+1;
v[now->right->layer].push_back(now->right->data);
q.push(now->right);
}
}
}
int main() {
int n;
scanf("%d",&n);
for(int i=0; i<n; i++) {
scanf("%d",&in[i]);
}
for(int i=0; i<n; i++) {
scanf("%d",&post[i]);
}
node* root=create(0,n-1,0,n-1); //建树
zOrder(root);
printf("%d",post[n-1]);
for(int i=2; i<=maxlayer; i++) {
if(i%2==0) {
for(int j=0; j<v[i].size(); j++) {
printf(" %d",v[i][j]);
}
} else {
for(int j=v[i].size()-1; j>=0; j--) {
printf(" %d",v[i][j]);
}
}
}
return 0;
}