要点1.根据后序和中序建立树得会
要点2.记录每层的元素得会,front 和last 还有 rear的关键点,即非递归求树高
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
int n,post[35],in[35];
struct Node{
int data;
Node *lchild,*rchild;
};
void indata(int p[]){
for(int i=0;i<n;++i) cin>>p[i];
}
Node *create(int post[],int in[],int len){
if(len==0) return NULL;
int i;
for(i=0;i<len;++i) {
if(in[i]==post[len-1]) break;
}
Node *root=new Node();
root->data=post[len-1];
root->lchild=create(&post[0],&in[0],i);
root->rchild=create(&post[i],&in[i+1],len-i-1);
return root;
}
void levelorder(Node *root){
queue<Node*> q,qu1,qu2;
stack<Node*> st1;
q.push(root);
int front=0,rear=1,last=1;
bool flag=false;
while(!q.empty()){
Node *temp=q.front();
if(flag){
qu1.push(temp);
}else{
st1.push(temp);
}
q.pop();
front++;
if(temp->lchild) {
q.push(temp->lchild);
rear++;
}
if(temp->rchild) {
q.push(temp->rchild);
rear++;
}
if(front==last) {
last=rear;
if(flag){
while(!qu1.empty()){
qu2.push(qu1.front());
qu1.pop();
}
}else{
while(!st1.empty()){
qu2.push(st1.top());
st1.pop();
}
}
flag=!flag;
}
}
while(!qu2.empty()){
cout<<qu2.front()->data;
qu2.pop();
if(!qu2.empty()) cout<<" ";
}
}
int main(){
cin>>n;
indata(in);
indata(post);
Node* root=create(post,in,n);
levelorder(root);
return 0;
}