1127 ZigZagging on a Tree

#include<iostream> 
#include<vector>
#include<queue>
using namespace std;
struct Node{
	int data,heighttt;
	Node* left;
	Node* right;
};
int n,heightt;
vector<int> in,pos,lev;
vector<Node*> le[31]; 
Node* build(int posl,int posr,int inl,int inr){
	if(posl>posr) return NULL;
	Node* root=new Node;
	root->data=pos[posr];
	root->left=NULL;
	root->right=NULL;
	int k;
	for(k=inl;k<=inr;k++){
		if(pos[posr]==in[k]){
			break;
		}
	}
	int numleft=k-inl;
	root->left=build(posl,posl+numleft-1,inl,k-1);
	root->right=build(posl+numleft,posr-1,k+1,inr);
	return root;
}
void leveltra(Node* root,int height){
	queue<Node*> q;
	root->heighttt=height;
	q.push(root);
	Node* now;
	while(q.empty()!=1){
		now=q.front();
		q.pop();
		le[now->heighttt].push_back(now);
		if(now->left!=NULL){
			now->left->heighttt=now->heighttt+1;q.push(now->left);
		} 
		if(now->right!=NULL){
			now->right->heighttt=now->heighttt+1;q.push(now->right);
		} 
	}
	heightt=now->heighttt;
}
void pre(Node* root){
	if(root==NULL) return;
	cout<<root->data<<' ';
	pre(root->left);
	pre(root->right);
	
}
int main(){
	#ifdef ONLINE_JUDGE
	#else
	freopen("in.txt","r",stdin);
	#endif
	cin>>n;
	for(int i=0;i<n;i++){
		int temp;
		cin>>temp;
		in.push_back(temp);
	}
	for(int i=0;i<n;i++){
		int temp;
		cin>>temp;
		pos.push_back(temp);
	}
	Node* root;
	root=build(0,n-1,0,n-1);
	leveltra(root,1);
	for(int i=1;i<=heightt;i++){
		if(i==1)
		cout<<le[i][0]->data;
		else
		{
			if(i%2==0){
				for(int j=0;j<le[i].size();j++){
					cout<<' '<<le[i][j]->data;
				}
			}else{
				for(int j=le[i].size()-1;j>=0;j--){
					cout<<' '<<le[i][j]->data;
				}
			}
		}
		
	}
	cout<<endl;
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值