1、题目
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
2、我的思路
1、根据中序和后序序列建树;2、层序遍历该树,层数为偶数的节点直接打印,层数为奇数的同一层节点压入栈中;3、每次遍历到偶数层最左边的节点时,先将栈中的节点依次打印出来,再打印本层节点;4、为防止最后一层时层数为奇数,遍历完若栈不为空,要将栈中元素依次打印出来。
3、我的代码
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
const int MAXN=35;
int n;
struct Node
{
int data;
int hegiht;
Node *left;
Node *right;
};
int postSeq[MAXN];
int inSeq[MAXN];
stack<int> st;
Node* createT(int postL,int postR,int inL,int inR)
{
if(inL>inR)
return NULL;
Node* root=new Node;
root->data=postSeq[postR];
root->left=NULL;
root->right=NULL;
int k;
for(int i=0;i<n;i++)
{
if(inSeq[i]==postSeq[postR])
{
k=i;
break;
}
}
int leftNum=k-inL;
root->left=createT(postL,postL+leftNum-1,inL,k-1);
root->right=createT(postL+leftNum,postR-1,k+1,inR);
return root;
}
int countN=0;
void zigOrder(Node* s)
{
queue<Node*> Q;
Q.push(s);
printf("%d",s->data);
countN++;
if(countN!=n)
printf(" ");
while(!Q.empty())
{
Node* top=Q.front();
Q.pop();
int h=top->hegiht;
if(h!=1&&h%2!=0)
st.push(top->data);
else if(h%2==0)
{
int size=st.size();
if(st.size()!=0)
for(int i=0;i<size;i++)
{
printf("%d",st.top());
st.pop();
countN++;
if(countN!=n)
printf(" ");
}
printf("%d",top->data);
countN++;
if(countN!=n)
printf(" ");
}
if(top->left!=NULL)
{
top->left->hegiht=top->hegiht+1;
Q.push(top->left);
}
if(top->right!=NULL)
{
top->right->hegiht=top->hegiht+1;
Q.push(top->right);
}
}
int size=st.size();
if(st.size()!=0)
for(int i=0;i<size;i++)
{
printf("%d",st.top());
st.pop();
countN++;
if(countN!=n)
printf(" ");
}
}
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&inSeq[i]);
}
for(int i=0;i<n;i++)
{
scanf("%d",&postSeq[i]);
}
Node *root=createT(0,n-1,0,n-1);
root->hegiht=1;
zigOrder(root);
return 0;
}