我参考其他的:
#include<iostream>
#include<queue>
using namespace std;
typedef struct node
{
int val;
node *left;
node *right;
}node;
bool flag;
queue<node*> q;
node* rebuild(int *post,int *in,int length)
{
node *root=new node();
root->val=post[length-1];
root->left=NULL;
root->right=NULL;
int index;
for(index=0;index<length;index++)
{
if(in[index]==root->val)
break;
}
//printf("%d\n",index);
if(index>0)
{
root->left=rebuild(post,in,index);
}
if(length-1-index>0)
{
root->right=rebuild(post+index,in+index+1,length-index-1);
}
return root;
}
void print_pre(node *root)
{
if(root==NULL)
return;
else
{
q.push(root);
while(!q.empty())
{
node *top=q.front();
if(top==root)
printf("%d",top->val);
else
printf(" %d",top->val);
q.pop();
if(top->left!=NULL)
{
q.push(top->left);
}
if(top->right!=NULL)
{
q.push(top->right);
}
}
}
}
int main()
{
//freopen("test2.txt","r",stdin);
int n,i;
cin>>n;
flag=false;
int *post=new int[n];
int *in=new int[n];
for(i=0;i<n;i++)
{
cin>>post[i];
}
for(i=0;i<n;i++)
cin>>in[i];
node *root;
root=rebuild(post,in,n);
print_pre(root);
return 0;
}
lv_zj的:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <queue>
using namespace std;
class A
{
public:
struct node
{
int no;
node *lchild;
node *rchild;
};
void init();
void run();
void generate_tree(vector<int>pt,vector<int> it,node **r);
void level_order();
vector<int> posttree,intree;
int n;
node *tree;
};
template<typename T>
class getn
{
public:
const T operator()()
{
T t;
cin>>t;
return t;
}
};
void A::level_order()
{
queue<node*> qu;
node *r;
r=tree;
if(r!=NULL) {qu.push(r);cout<<r->no;}
while(!qu.empty())
{
r=qu.front();qu.pop();
if(r->lchild!=NULL)
{
cout<<" "<<r->lchild->no;
qu.push(r->lchild);
}
if(r->rchild!=NULL)
{
cout<<" "<<r->rchild->no;
qu.push(r->rchild);
}
delete r;
}
}
void A::generate_tree(vector<int>pt,vector<int> it,node **r)
{
if(pt.size()==0&&it.size()==0)
{
*r=NULL;
return;
}
vector<int> pt1,pt2,it1,it2;
int no=pt.back();
int k=find(it.begin(),it.end(),no)-it.begin();
copy(pt.begin(),pt.begin()+k,back_inserter(pt1));
copy(pt.begin()+k,pt.end()-1,back_inserter(pt2));
copy(it.begin(),it.begin()+k,back_inserter(it1));
copy(it.begin()+k+1,it.end(),back_inserter(it2));
node *pnode=new node;
pnode->no=no;
*r=pnode;
generate_tree(pt1,it1,&(pnode->lchild));
generate_tree(pt2,it2,&(pnode->rchild));
}
void A::init()
{
cin>>n;
generate_n(back_inserter(posttree),n,getn<int>());
generate_n(back_inserter(intree),n,getn<int>());
}
void A::run()
{
init();
generate_tree(posttree,intree,&tree);
level_order();
}
int main()
{
// freopen("test.in","r",stdin);
A *a=new A;
a->run();
return 0;
}