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

看看先序创建,遍历二叉树哪错了,谢谢!?

zhufeifei 发布于 2008-11-11 12:52, 1430 次点击
#include<stdio.h>
typedef char TElemType;
typedef struct BiTNode
{
        TElemType data;
        struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;

/*递归创建一个二叉树*/
void createBiTree(BiTree t)
{
        char c;
        c = getchar();
        if(c == 's')
        {
                t = NULL;
        }
        else
        {
                t = (BiTree)malloc(sizeof(BiTNode));
                t -> data = c;
                createBiTree(t -> lchild);
                createBiTree(t -> rchild);
        }
}

/*先序遍历二叉树*/
void preOrder(BiTree t)
{
        if(t)
        {
            printf("%c", t -> data);
            preOrder(t -> lchild);
            preOrder(t -> rchild);
        }
        else
                printf("this is a empty tree!");
}
int main()
{
        BiTree t = NULL;
        clrscr();
        printf("create a tree:");
        createBiTree(t);
        printf("preOrder the tree:");
        preOrder(t);
        getch();
        return 0;
}
4 回复
#2
hbcfxz2008-11-13 17:10
感觉你的递归创建二叉树好像有点问题
#3
fp1512010-12-22 23:43
你没有包含头文件 <stdlib.h>
2.你的那个getchar 写错了
3.clrscr(); 把这个删掉
#4
fp1512010-12-22 23:44
程序代码:
#include<stdio.h>
#include<stdlib.h>
typedef char TElemType;
typedef struct BiTNode
{
        TElemType data;
        struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;

/*递归创建一个二叉树*/
void createBiTree(BiTree t)
{
        char c;
        c = getchar();
        if(c == 's')
        {
                t = NULL;
        }
        else
        {
                t = (BiTree)malloc(sizeof(BiTNode));
                t -> data = c;
                createBiTree(t -> lchild);
                createBiTree(t -> rchild);
        }
}

/*先序遍历二叉树*/
void preOrder(BiTree t)
{
        if(t)
        {
            printf("%c", t -> data);
            preOrder(t -> lchild);
            preOrder(t -> rchild);
        }
        else
                printf("this is a empty tree!");
}
int main()
{
        BiTree t = NULL;
      
        printf("create a tree:");
        createBiTree(t);
        printf("preOrder the tree:");
        preOrder(t);
        getchar();
        return 0;
}
#5
灿烂烟火2011-06-13 22:19
修改后的函数如下:
/*递归创建一个二叉树*/
 BiTree createBiTree(BiTree t)
 {
         char c;
         c = getchar();
         if(c == 's')
         {
                 t = NULL;
         }
         else
         {
                 t = (BiTree)malloc(sizeof(BiTNode));
                 t -> data = c;
                 createBiTree(t -> lchild);
                 createBiTree(t -> rchild);
         }
         return t;
 }
1