二叉树重构

给你一颗真二叉树(节点要么没有孩子,要么有两个孩子)的前序和后序遍历输出中序遍历序列。


/*************************************************************************
    > File Name: Euler.cpp
    > Author: acvcla
    > QQ: 
    > Mail: acvcla@gmail.com 
    > Created Time: 2014年10月30日 星期四 11时19分11秒
 ************************************************************************/
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn=4000000+5;
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
struct tree
{
	int date;
	tree *l,*r;
	tree(int val=0):date(val){
		l=r=0;
	}
}M[maxn];
int cnt;
tree *newnode(int val){
	M[cnt].l=M[cnt].r=0;
	M[cnt].date=val;
	cnt++;
	return &M[cnt-1];
}
int A[maxn],B[maxn],ans[maxn],cot,n,pos1[maxn],pos2[maxn];
tree* built(int l,int r,int cur){
	tree *now=NULL;
	now=newnode(B[r]);
	if(l==r)return now;
	++cur,--r;
	now->l=built(l,pos1[A[cur]],cur);
	now->r=built(pos1[A[cur]]+1,r,pos2[B[r]]);
	return now;
}
struct V
{
	void operator () (int x){
		ans[++cot]=x;
	}
};
template<typename T>
void dfs(tree *p,T &vist){
	if(!p)return;
	dfs(p->l,vist);
	vist(p->date);
	dfs(p->r,vist);
}
char ch;
void read(int &x){
	x=ch=0;
	while(ch<'0'||ch>'9')ch=getchar();
	while(ch>='0'&&ch<='9'){
		x=(x<<3)+(x<<1)+ch-'0';
		ch=getchar();
	}
}
int main(){
		while(~scanf("%d",&n)){
			rep(i,1,n){
				read(A[i]);
				pos2[A[i]]=i;
			}
			rep(i,1,n){
				read(B[i]);
				pos1[B[i]]=i;
			}
			cnt=cot=0;
			tree *root=built(1,n,1);
			V cacu;
			dfs(root,cacu);
			rep(i,1,cot)printf("%d%c",ans[i],i==cot?'\n':' ');
		}
		return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值