二叉树已知先序序列(后序序列)、中序序列求解后序序列(先序序列)

杭电原题:http://acm.hdu.edu.cn/showproblem.php?pid=1710

先根据先序中序序列建一个二叉树,然后后序遍历二叉树

#include <stdio.h>

#include <stdlib.h>
#include <string.h>
typedef struct node
{
int value;
struct node *pLeft;
struct node *pRight;
}Tree,*pTree;
int pre[1002];
int in[1002];
int post[1002];
int k;
void PostOrderTraverse(pTree pRoot)
{
if(pRoot->pLeft!=NULL)
PostOrderTraverse(pRoot->pLeft);
if(pRoot->pRight!=NULL)
PostOrderTraverse(pRoot->pRight);
post[k++]=pRoot->value;

}

//pre_start 先序序列第一个元素下标

//pre_end 先序序列最后一个元素下标

//in_start 中序序列第一个元素下标

//in_end 中序序列最后一个元素下标

void PreInCreateTree(pTree &pRoot,int pre_start,int pre_end,int in_start,int in_end)
{
pRoot=(pTree)malloc(sizeof(Tree));
pRoot->value=pre[pre_start];
int rootIndex;//根节点在中序序列中的下标
int i;
for(i=in_start;i<=in_end;i++)
{
if(pRoot->value==in[i])
{
rootIndex=i;
break;
}
}
if(rootIndex!=in_start)
{
PreInCreateTree(pRoot->pLeft,pre_start+1,pre_start+(rootIndex-in_start),in_start,rootIndex-1);
}
else
{
pRoot->pLeft=NULL;
}
if(rootIndex!=in_end)
{
PreInCreateTree(pRoot->pRight,pre_start+(rootIndex-in_start)+1,pre_end,rootIndex+1,in_end);
}
else
{
pRoot->pRight=NULL;
}
}
int main()
{
int i,n;
while(~scanf("%d",&n))
{
memset(pre,0,sizeof(pre));
memset(in,0,sizeof(in));
memset(post,0,sizeof(post));
for(i=0;i<n;i++)
scanf("%d",&pre[i]);
for(i=0;i<n;i++)
scanf("%d",&in[i]);
pTree pRoot;
PreInCreateTree(pRoot,0,n-1,0,n-1);
k=0;
PostOrderTraverse(pRoot);
for(i=0;i<k-1;i++)
printf("%d ",post[i]);
printf("%d\n",post[i]);
}
return 0;

}

另附由后序序列、中序序列求解先序序列的代码

相应的修改一些代码即可实现

void InPostCreateTree(pTree &pRoot,int in_start,int in_end,int post_start,int post_end)
{
pRoot=(pTree)malloc(sizeof(Tree));
pRoot->value=post[post_end];
int rootIndex;
int i;
for(i=in_start;i<=in_end;i++)
{
if(pRoot->value==in[i])
{
rootIndex=i;
break;
}
}
if(rootIndex!=in_start)
{
InPostCreateTree(pRoot->pLeft,in_start,rootIndex-1,post_start,post_start+(rootIndex-in_start)-1);
}
else
pRoot->pLeft=NULL;
if(rootIndex!=in_end)
{
InPostCreateTree(pRoot->pRight,rootIndex+1,in_end,post_start+(rootIndex-in_start),post_end-1);
}
else
pRoot->pRight=NULL;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hober.z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值