LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
12
返回列表 发新帖
楼主: Xiangbuilder

建立二叉树的算法

[复制链接]
发表于 2005-8-20 17:04:07 | 显示全部楼层
Post by moyanjwb
是因为你下一个字符接受的是回车,按下面的改可以,另外把你的结束标志换成除空格外的另一个字符

#include <stdio.h>

#include <stdlib.h>
typedef char DataType;
typedef struct node
{
        DataType data;
        struct node *lchild, *rchild;
} BinTNode;
typedef BinTNode *BinTree;
void CreateBinTree (BinTree *T)
{
        char ch;
        printf("%s\n","lease enter");
        scanf("\n%c",&ch);
        if (ch=='#')
        {
                *T=NULL;
        //        printf ("abc");
        }
        else
        {
                *T=(BinTNode *)malloc(sizeof(BinTNode));
                (*T)->data=ch;
                CreateBinTree (&((*T)->lchild));  //1
                CreateBinTree (&((*T)->rchild));  //2
               // printf ("aaa");
        }
}
void main ()
{
        BinTree root;
        CreateBinTree (&root);
}
已经编译运行过了,可以。

上面说的方法可以,或者你清除一下缓冲区也可以,改后的代码如下:
#include <stdio.h>

#include <stdlib.h>
typedef char DataType;
typedef struct node
{
        DataType data;
        struct node *lchild, *rchild;
} BinTNode;
typedef BinTNode *BinTree;
void CreateBinTree (BinTree *T)
{
        char ch;
        printf("%s\n","lease enter");
        scanf("%c",&ch);
        while(getchar()!='\n')                  //清楚缓冲区
                ;
        if (ch==' ')
        {
                *T=NULL;
        //        printf ("abc");
        }
        else
        {
                *T=(BinTNode *)malloc(sizeof(BinTNode));
                (*T)->data=ch;
                CreateBinTree (&((*T)->lchild));  //1
                CreateBinTree (&((*T)->rchild));  //2
               // printf ("aaa");
        }
}
void main ()
{
        BinTree root;
        CreateBinTree (&root);
}
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表