个人学习记录,代码难免不尽人意。
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<vector>
#include<algorithm>
#include<cmath>
#include<queue>
#include<string>
using namespace std;
const int maxn=35;
int inorder[maxn];
int postorder[maxn];
struct node{int data;node* lchild;node* rchild;
};
node* newnode(int data){node* root=new node;root->data=data;root->lchild=NULL;root->rchild=NULL;return root;
}
node* create(int postl,int postr,int inl,int inr){if(postl>postr) return NULL;int head=postorder[postr];node* root=newnode(head);int index;for(int i=inl;i<=inr;i++){if(inorder[i]==head){index=i;break;}}int left=index-inl;root->lchild=create(postl,postl+left-1,inl,inl+left);root->rchild=create(postl+left,postr-1,index+1,inr);return root;
}
int zorder[maxn];
void BFS(node* root,int n){int num=0;bool flag=true;queue<node*> q;vector<node*> v;v.push_back(root);while(num<n){if(flag){for(int i=0;i<v.size();i++){node* now=v[i];if(now->lchild!=NULL) q.push(now->lchild);if(now->rchild!=NULL) q.push(now->rchild);}for(int i=v.size()-1;i>=0;i--){node* now=v[i];zorder[num++]=now->data;}v.clear();flag=false;}else{while(!q.empty()){node* now=q.front();zorder[num++]=now->data;q.pop();if(now->lchild!=NULL) v.push_back(now->lchild);if(now->rchild!=NULL) v.push_back(now->rchild);}flag=true;}}
}
int main(){int n;scanf("%d",&n);for(int i=0;i<n;i++){scanf("%d",&inorder[i]);}for(int i=0;i<n;i++){scanf("%d",&postorder[i]);}node* root=create(0,n-1,0,n-1);BFS(root,n);for(int i=0;i<n;i++){printf("%d",zorder[i]);if(i!=n-1) printf(" ");else printf("\n");}
}
这道题首先需要利用中序遍历和后序遍历来构建二叉树,然后再进行层次遍历的变式输出。
一开始我觉得我的构造肯定会出错,因为我这一块总是记得迷迷糊糊的,但是很意外的是这次我的思路异常清晰。
然后关于“z字遍历”我的做法是这样的,用队列来正向输出,然后用了一个vector来模拟栈来反向输出,用一个bool变量来控制输出类型,每次正向或者反向输出之后都将bool取反,具体操作可以看代码,我觉得这个题我的做法应该是比较优秀的。