标签:contains scan either sizeof mon height mil border ges
题链;http://acm.hdu.edu.cn/showproblem.php?pid=1710

9 1 2 4 7 3 5 8 9 6 4 7 2 1 8 5 9 3 6
7 4 2 8 9 5 6 3 1
然后这个根把中序分为两半,左边是左子树,右边是右子树。
然后递归下就ok了。
#include <cstdio>
#include <algorithm>
using namespace std;
struct tree
{
struct tree* l;
struct tree* r;
int val;
tree()
{
l=NULL;
r=NULL;
}
};
int pre[1010],in[1010];
int n;
tree* root;
void build(int num,int l,int r,tree *rt)//pre num in_l in_r
{
int flag=-1;
while(flag==-1)
{
for(int i=l;i<=r;i++)
{
if(pre[num]==in[i])
flag=i;
}
if(flag==-1)
num++;
}
if(flag-l>0)
{
rt->l=(tree*)malloc(sizeof(tree));
*(rt->l)=tree();
build(num+1,l,flag-1,rt->l);
}
if(r-flag>0)
{
rt->r=(tree*)malloc(sizeof(tree));
*(rt->r)=tree();
build(num+1,flag+1,r,rt->r);
}
rt->val=pre[num];
}
void post(tree* nw)
{
if(nw->l!=NULL)
post(nw->l);
if(nw->r!=NULL)
post(nw->r);
if(nw==root)
printf("%d",nw->val);
else
printf("%d ",nw->val);
}
void del(tree* nw)
{
if(nw->l!=NULL)
del(nw->l);
if(nw->r!=NULL)
del(nw->r);
free(nw);
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
for(int i=0;i<n;i++)
scanf("%d",&pre[i]);
for(int i=0;i<n;i++)
scanf("%d",&in[i]);
root=(tree*)malloc(sizeof(tree));
*root=tree();
build(0,0,n-1,root);
post(root);
puts("");
del(root);
}
return 0;
}
hdu 1710 Binary Tree Traversals 前序遍历和中序推后序
标签:contains scan either sizeof mon height mil border ges
原文地址:http://www.cnblogs.com/yfceshi/p/7191127.html