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

杭电原题: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;
}

你可能感兴趣的:(二叉树,遍历,杭电,序列转换)