题意
给定中序和后序,求Z型遍历的层序
题解
通过中序,后序建树,然后层序遍历时进行相应处理
要点是在队列之中分离出每一层的顶点
cur存储当前层有多少顶点,在对其进行遍历的过程中利用num记录下一层的顶点个数,从而达到分离的目的
将每层的顶点分离后,根据深度的奇偶性正序或逆序输出即可
源码
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
int inorder[35];
int postorder[35];
struct node{
int val;
node* lchild;
node* rchild;
node(int x){
val=x;
lchild=NULL;
rchild=NULL;
}
};
int m;
node* buildTree(int root,int inl,int inr){
if(inl>inr) return NULL;
node* n=new node(postorder[root]);
int pos;
for(int i=0;i<m;i++){
if(inorder[i]==postorder[root]){
pos=i;
break;
}
}
n->rchild=buildTree(root-1,pos+1,inr);
n->lchild=buildTree(root-(inr-pos)-1,inl,pos-1);
return n;
}
void levelorder(node* root){
queue<node*>Q;
vector<int>help;
vector<int>allnumber;
Q.push(root);
int next=0,cur=1,depth=1;
while(!Q.empty()){
help.clear();
while(cur--){
node* temp=Q.front();
Q.pop();
help.push_back(temp->val);
if(temp->lchild){
Q.push(temp->lchild);
next++;
}
if(temp->rchild){
next++;
Q.push(temp->rchild);
}
}
cur=next;
next=0;
if(depth%2==0){
for(int i=0;i<help.size();i++){
allnumber.push_back(help[i]);
}
}else{
for(int i=help.size()-1;i>=0;i--){
allnumber.push_back(help[i]);
}
}
depth++;
}
for(int i=0;i<allnumber.size()-1;i++){
cout<<allnumber[i]<<" ";
}
cout<<allnumber[allnumber.size()-1];
}
int main(){
cin>>m;
for(int i=0;i<m;i++) cin>>inorder[i];
for(int i=0;i<m;i++) cin>>postorder[i];
node* s=buildTree(m-1,0,m-1);
levelorder(s);
return 0;
}