7-8 ZigZagging on a Tree (20分)
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.
zigzag.jpg
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
给你解释下题目:
给你中序遍历,后续遍历,建树,然后层序输出,但是这个层序输出有点猫腻:S型输出(正常都是从上到家,从左到右)
- 两个栈搞定!
- 自己在选拔时候想的,大呼过瘾 ,一句卧槽行天下!
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
struct node* left;
struct node* right;
};
const int maxn=100000;
int xian[maxn];
int hou[maxn];
int zhong[maxn];
int n;
void build(struct node* &root,int l,int r,int ll,int rr ){
if(l<=r){
int th=l;
while(zhong[th]!=hou[rr])th++;
root=new struct node;
root->left=NULL;
root->right=NULL;
root->data=hou[rr];
int leng=th-l;
build(root->left,l,th-1,ll,ll+leng-1);
build(root->right,th+1,r,ll+leng,rr-1);
}
}
void xianxu(struct node* root ){
if(root==NULL)return ;
cout<<root->data<<' ';
xianxu(root->left);
xianxu(root->right);
}
/// 变态版的层序遍历!
vector <int >ve;
stack<struct node* >sta1,sta2;
/// 自己画个图就能明白 然后说卧槽
void ceng(struct node* root){
sta1.push(root);
/**
sta1 奇数层
sta2 偶数层
ve 最终要输出的顺序
*/
struct node* nn;
/// 这两个栈用的太爽了!!!
while(!sta1.empty()||!sta2.empty()){
while(!sta1.empty()){
nn=sta1.top();
sta1.pop();
ve.push_back(nn->data);
/// 一定要先右边 ,再左边
if(nn->right){
sta2.push(nn->right);
}
if(nn->left){
sta2.push(nn->left);
}
}
while(!sta2.empty()){
nn=sta2.top();
sta2.pop();
ve.push_back(nn->data );
/// 一定要先左边 ,再右边
if(nn->left){
sta1.push(nn->left);
}
if(nn->right){
sta1.push(nn->right);
}
}
}
}
main(){
cin>>n;
for(int a=0;a<n;a++){
cin>>zhong[a];
}
for(int a=0;a<n;a++){
cin>>hou[a];
}
struct node* root=NULL;
build(root,0,n-1,0,n-1);
ceng(root);
for(int a=0;a<ve.size();a++){
cout<<ve[a];
if(a!=ve.size()-1)cout<<' ';
}
}