已知一棵二叉树的中序序列和后序序列,写一个建立该二叉树的二叉链表存储结构的算法

 

已知一棵二叉树的中序序列和后序序列,写一个建立该二叉树的二叉链表存储结构的算法

#define N 10 //二叉树节点的个数

char postorderstr[]={};//
后序序列
char inorderstr[]={};//中序序列

Stastus Creat_BiTree(BiTree &T,int s1,int e1,int s2,int e2)

//s1,e1为子树序列在中序序列中的起始位置,s2,e2为子树序列在后序序列中的起始位置

{

  if(!(T=(BiTNode *)malloc(sizeof (BiTNode)))) exit(OverFollow)

   T->data=postorderstr[e2];

   T->Lchild=T->Rchild=null;

   if(s1!=e1)//s1!=e1时为非叶子节点,创建子树

     {

t=FindPosition(postorderstr[e2]);

if(t!=s1)//t=s1时,该节点没有左子树

{CreatBiTree(T->Lchild,s1,t-1,s2,s2+(t1-1-s1)); }

//子树序列长度是一定的,所以在中序中易知子树序列长度为t1-1-s1,那么在后序序列中的起始位置也易知

if(t!=e1)//当时,该节点没有右子树

{CreatBiTree(T->Rchild,t1+1,e1,(e2-1)-(e1-(t+1)),e2-1);}

//注释同上

}

}

 

intFindPosition(char c)

//查找字符c在中序序列中的位置

{

  for(i=0;i<N;i++)

{

  if(inorderstr[i]==c)

   break;

}

  return i-1;

}

 

posted @ 2006-01-22 13:36  火火  阅读(4315)  评论(0编辑  收藏  举报