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

建立一个二叉树并完成树的遍历程序

nowander 发布于 2011-11-19 01:26, 1058 次点击
#include "stdio.h"
typedef char ElemType;
#define MAXNUM 150

/* 二叉树结点定义 */
typedef struct BTNode
{
    ElemType data;         /* data field */
    struct BTNode *lchild;
    struct BTNode *rchild;   
} BTNode;

/* 辅助的二叉树索引数组 */
BTNode *p[MAXNUM+1];

/* 根据用户输入创建二叉树 */
/* 二叉树结点信息:数据域,以及在完全二叉树中的索引值 */
BTNode *Create_BiTree(void)
{
        BTNode* t = NULL;
        int i;
        int j;
        char ch;
   
        printf("\n enter i, ch :");
        scanf("%d,%c", &i, &ch);
        
        while (i != 0 && ch != '#' )
        {
            BTNode* s = (BTNode*)malloc(sizeof(BTNode));
            s->data = ch;
            s->lchild = s->rchild = NULL;
            
            p[i] = s;
            
            if ( i == 1 )
                t = s;
            else
            {
                j = i/2;
               
                if ( i%2 == 0 )
                    p[j]->lchild = s;
                else
                    p[j]->rchild = s;
            }
            printf("\n enter i, ch :");
            scanf("%d,%c", &i, &ch);
        }
        
        return t;
}

int main(void)
{
    BTNode* t;
    t = Create_BiTree();
/*   
    preorder(t);
    printf(" preorder\n");
    preorder_recursive(t);
    printf(" preorder_recursive\n");

    Inorder(t);
    printf(" Inorder\n");
    Inorder_recursive1(t);
    printf(" Inorder_recursive1\n");
    Inorder_recursive2(t);
    printf(" Inorder_recursive2\n");


    Postorder(t);
    printf(" Postorder\n");
    Postorder_recursive(t);
    printf(" Postorder_recursive\n");

    LevelOrder(t);
    printf(" LevelOrder\n");
*/   
    getchar();
    getchar();

    return 0;

}


 void preorder(BTNode *bt)
{
     if (bt)
   {
           printf("%c ",bt->data);
      preorder(bt->lchild);
      preorder(bt->rchild);
    }
}
void Inorder(BTNode *bt)
{
  if (bt)
  {
      Inorder(bt->lchild);
    printf("%c ",bt->data); /* 访问根结点 */
    Inorder(bt->rchild);
  }
} /* inorder */
 void Postorder(BTNode *bt)
{
     if (bt)
     {
         Postorder(bt->lchild);
      Postorder(bt->rchild);
      printf("%c ",bt->data);
  }
}
--------------------------------------------------------------------------
在WIN-TC上执行总是看不到结果,加getch()或while(1)则提示有不可到达程序这是怎么回事??????



2 回复
#2
qq6054122542011-11-19 09:19
void preorder(BTNode *bt)
没有声明吧
#3
取出802011-12-15 20:04
要嘛你把子函数写在前面,要嘛你在前面先声明函数
1