#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<list>
#include<stack>
using namespace std;
template<class T>
class Queue{
private:
list<T>queue;
public:
Queue(){}
~Queue(){}
int Empty(){return queue.empty();}
int Size(){ return queue.size();}
void Push(const T&item){queue.push_back(item);}
T Pop(){T item=queue.front(); queue.pop_front(); return item;}
void Clear(){queue.clear();}
};
template<class T>
struct BTNode{
T data;
BTNode*left,*right;
BTNode(const T&item=T(),BTNode*lp=NULL,BTNode*rp=NULL):data(item),left(lp),right(rp){
}
};
template<class T>
BTNode<T>*GetNode(const T&item,BTNode<T>*lp=NULL,BTNode<T>*rp=NULL){
BTNode<T>*p;
p=new BTNode<T>(item,lp,rp);
if(p==NULL){
cout<<"the new is faliure"<<endl;
exit(1);
}
return p;
}
template<class T>
void level(const BTNode<T>*t,int n){
if(t==NULL)return ;
Queue<const BTNode<T>*>q;
q.Push(t);
int i=0;
while(!q.Empty()){
t=q.Pop();
i++;
if(i==n){
cout<<t->data;
}else{
cout<<t->data<<" ";
}
if(t->left)q.Push(t->left);
if(t->right)q.Push(t->right);
}
}
template<class T>
BTNode<T>*IOMAkeLinked(const T*pre,const T*il,int size)
{
if(size<=0)return 0;
BTNode<T>*left,*right,*t;
const T*rl;
int k;
for(rl=il;rl<il+size;rl++)
{
if(*rl==*pre)
{
break;
}
}
k=rl-il;
right=IOMAkeLinked(pre+1,il,k);
left=IOMAkeLinked(pre+k+1,il+k+1,size-k-1);
t=GetNode(*pre,left,right);
return t;
}
template<class T>
BTNode<T>*MAxlingked(int a[],int n){
if(n==0)return 0;
Queue<BTNode<T>*>q;
BTNode<T>*t=GetNode(a[0]);
BTNode<T>*parent,*child;
q.Push(t);
int i=0;
while(!q.Empty()){
parent=q.Pop();
if(2*i+1<n&&a[2*i+1]!=T()){
child=GetNode(a[2*i+1]);
parent->right=child;
q.Push(child);
}
if(2*i+2<n&&a[2*i+2]!=T()){
child=GetNode(a[2*i+2]);
parent->left=child;
q.Push(child);
}
i++;
while(i<n&&a[i]==T())i++;
}
return t;
}
int main()
{
int n;
BTNode<int>*t3,*t5;
int pre[105];
int Inor[105];
memset(pre,0,sizeof(pre));
memset(Inor,0,sizeof(Inor));
cin>>n;
for(int i=0;i<n;i++){
cin>>Inor[i];
}
for(int i=0;i<n;i++){
cin>>pre[i];
}
t3=IOMAkeLinked(pre,Inor,n);
level(t3,n);
return 0;
}
PTA团体程序设计天梯赛-L2-011 玩转二叉树
最新推荐文章于 2024-03-07 20:48:10 发布