注册 登录
编程论坛 数据结构与算法

谁能帮我讲解一下这个非递归法建立二叉树的思路

赤壁男儿 发布于 2010-10-08 21:15, 682 次点击
//建立二叉树,非递归算法,输入时按层次输入。以“$ "结束,以“! "表示孩子为空。
#include   <stdio.h>
#include    <stdlib.h>
typedef     struct   bnode{
      char   data;
      struct   bnode   *lchild;
      struct   bnode   *rchild;
}BinNode;

BinNode   *root,   *s,   *q[100];


//非递归法建立二叉树
void Inittree()
{
      int   parent,   children;
      char   ch;
      parent=1;
      children=0;
      root=NULL;
      printf( "\nPlease   input   the   data: ");
      scanf( "%d ",&ch);     getchar();
   
    while(ch!= '$ ')
    {
          s=NULL;
          if   (ch!= '! ')
          {
                s=malloc(sizeof(BinNode));
                s-> rchild=NULL;
                s-> lchild=NULL;
                s-> data=ch;
          }
          children++;
          q[children]=s;
          if   (children==1)   
              root=s;
          else   
          {
              if(s!=NULL&&q[parent]!=NULL)  
              {
                      if   (children%2==0)
                              q[parent]-> lchild=s;
                      else
                              q[parent]-> rchild=s;
              }
              if(children%2==1)
                    parent++;
        }
        printf( "Please   input   the   data: ");
        scanf( "%c ",&ch);     getchar();
    }      
}

void preorder(BinNode   *root)
{
      if(root!=NULL)
      {
            printf( "%4c ",root-> data);
            preorder(root-> lchild);
            preorder(root-> rchild);
      }
}/*前序遍历*/
main()
{
        Inittree();
        preorder(root);
}
1 回复
#2
寒风中的细雨2010-10-14 19:33
能不能贴个图上来
1