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字遍历该二叉树
主要思路:步骤1.根据中序和后序建立二叉树:
后序最后面的结点为根节点然后再中序找到根节点的位置,其左侧就为左子树右侧就为右字树依次递归进行;
步骤2.根据二叉树进行Z字遍历:考虑第一层从右往左第二层从左往右很容易想到利用两个堆栈来实现,第一个堆栈出栈顺序相当于从右往左输出,为了使下一层从左往右输出,我们需要先将右孩子入到第二个栈再将左孩子入到第二个栈,依次进行就可以达到Z字遍历的效果。
AC代码:
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<stack>
#include<queue>
using namespace std;
const int maxn=31;
struct Node{
Node *leftchild,*rightchild;
int data;
};
int n;
int in[maxn],post[maxn];
Node *Create (int postl,int postr,int inl,int inr){
if(postl>postr){
return NULL;
}
Node *root=new Node;
root->data=post[postr];//根结点;
int k;
for(k=inl;k<=inr;k++){
if(in[k]==post[postr])
break;
}
int numl=k-inl;//左子书数
root->leftchild=Create(postl,postl+numl-1,inl,k-1);
root->rightchild=Create(postl+numl,postr-1,k+1,inr);
return root;
}
void ZigZagging (Node *root){
stack<Node *>st,st1;
printf("%d",root->data);
if(root->rightchild!=NULL){
st.push(root->rightchild);
}
if(root->leftchild!=NULL){
st.push(root->leftchild);
}
while(!st.empty()||!st1.empty())
{while(!st.empty()){
Node* now=st.top();
printf(" %d",now->data);
st.pop();
if(now->leftchild!=NULL){
st1.push(now->leftchild);
}
if(now->rightchild!=NULL){
st1.push(now->rightchild);
}
}
while(!st1.empty()){
Node* now=st1.top();
printf(" %d",now->data);
st1.pop();
if(now->rightchild!=NULL){
st.push(now->rightchild);
}
if(now->leftchild!=NULL){
st.push(now->leftchild);
}
}
}}
int main(){
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);
ZigZagging(root);
system("pause");
return 0;
}