PTA团体程序设计天梯赛-L2-006 树的遍历

#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*postl,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==*(postl+size-1))
   		{
   			break;
		}
	}
	k=rl-il;
	left=IOMAkeLinked(postl,il,k);
	right=IOMAkeLinked(postl+k,il+k+1,size-k-1);
	t=GetNode(*(postl+size-1),left,right);
	return t;
}
int main()
{
	int n;
	BTNode<int>*t3;
	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>>pre[i];
	}
	for(int i=0;i<n;i++){
    	cin>>Inor[i];
	}
	t3=IOMAkeLinked(pre,Inor,n);
	level(t3,n);
	return 0;
 } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值