您的位置:首页 > 其它

1127. ZigZagging on a Tree (30) 根据中+后输出层序遍历

2017-11-13 22:01 330 查看
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

模板建立好树
然后奇数层倒着输出,偶数层正向输出

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<queue>
#include<cstring>
#include<map>
using namespace std;

typedef struct tree{
int num;
struct tree *left,*right;
}tree,*linktree;
linktree creat(int *hou,int *zhong,int n){
if(n<=0) return NULL;
linktree t=new tree();
t->num=hou[n-1];
int index=0;
for(int i=0;i<n;i++){
if(zhong[i]==hou[n-1]){
index=i;
break;
}
}
t->left=creat(hou,zhong,index);
t->right=creat(hou+index,zhong+index+1,n-index-1);
return t;
}
vector<int> v[1000];
typedef pair<int,linktree> P;
void cengxu(linktree head){
queue<P> que;
que.push({1,head});
while(que.size()){
P p=que.front();
que.pop();
int num=p.first;
linktree fz=p.second;
if(fz->left!=NULL) {
que.push({num+1,fz->left});
v[num+1].push_back(fz->left->num);
}
if(fz->right!=NULL) {
que.push({num+1,fz->right});
v[num+1].push_back(fz->right->num);
}
}
}
int main(){
int n;
scanf("%d",&n);
int zhong[100],hou[100];
for(int i=0;i<n;i++){
scanf("%d",&zhong[i]);
}
for(int i=0;i<n;i++){
scanf("%d",&hou[i]);
}
linktree head=creat(hou,zhong,n);
cengxu(head);

printf("%d",head->num);
for(int i=2;i<=30;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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: