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
1、根据中序遍历和后续遍历建树,写了很多次了。
2、层次遍历,将每一次的结点放入对应的vector中存储。
3、格式化输出,根据层次的奇偶性。
#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
struct node{
int data;
int level;
node *lchild,*rchild;
};
int N;
int a[35];
int b[35];
vector<int> level[35];
int deep=0;
void creat_Tree(int l1,int r1,int l2,int r2,node* &t)
{
if(l1>r1)
return;
t=new node;
t->data=b[r2];
t->lchild=NULL;
t->rchild=NULL;
int i;
for(i=l1;i<=r1;i++)
if(a[i]==b[r2])
break;
creat_Tree(l1,i-1,l2,l2+i-1-l1,t->lchild);
creat_Tree(i+1,r1,l2+i-l1,r2-1,t->rchild);
}
void level_tra(node *root)
{
if(root==NULL)
return;
root->level=1;
queue<node*> que;
que.push(root);
while(!que.empty())
{
node *curr=que.front();
que.pop();
level[curr->level].push_back(curr->data);
deep=curr->level;
if(curr->lchild!=NULL)
{
curr->lchild->level=curr->level+1;
que.push(curr->lchild);
}
if(curr->rchild!=NULL)
{
curr->rchild->level=curr->level+1;
que.push(curr->rchild);
}
}
}
int main(){
cin>>N;
node *root=NULL;
for(int i=1;i<=N;i++)
scanf("%d",&a[i]);
for(int i=1;i<=N;i++)
scanf("%d",&b[i]);
creat_Tree(1,N,1,N,root);
level_tra(root);
for(int i=1;i<=deep;i++)
{
if(i%2==0)
for(int j=0;j<level[i].size();j++)
if(i==deep&&j==level[i].size()-1)
printf("%d\n",level[i][j]);
else
printf("%d ",level[i][j]);
else
for(int j=level[i].size()-1;j>=0;j--)
if(i==deep&&j==0)
printf("%d\n",level[i][j]);
else
printf("%d ",level[i][j]);
}
return 0;
}