1127 ZigZagging on a Tree (30分)

要点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;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值