关于二叉树创建时遇到的问题的解决

来源:互联网 发布:php调用服务器exe程序 编辑:程序博客网 时间:2024/05/29 16:19

之前在创建二叉树时,遇到了一些问题,因为这个忽视的问题而导致在写计算二叉树的叶子数时出现死循环,今天在老师的帮助下找到了问题所在:

之前的创建二叉树的代码为:

int CreateBiTree(BiTree *T){    char ch;    printf("\n\t\t\t\t\t  ch:");    fflush(stdin);    scanf("%c",&ch);    if(ch == 'Z')    {        T = NULL;    }    else    {        if(!(*T = (BiTNode *)malloc(sizeof(BiTNode))))        {            exit(OVERFLOW);        }        printf("\t\t\t\t\t(*T)->data = ch:");        (*T)->data = ch; //生成根节点        printf("  lchild:");        CreateBiTree(&(*T)->lchild);    //生成左子树        printf("\t\t\t\t\t  rchild:");        CreateBiTree(&(*T)->rchild);    //生成右子树    }    return OK;}//创建二叉树
计算叶子结点的代码为:

int CountBiTreeLeaf(BiTree T){    if(T == NULL)    {        printf("\nT == NULL");        return 0;    }    else if((T->lchild == NULL) && (T->rchild == NULL))    {        printf("\nT->lchild == NULL || T->rchild == NULL");        printf("\nT->data=%c",T->data);        return 1;    }    else    {        printf("\nCountBiTreeLeaf(T->lchild) + CountBiTreeLeaf(T->rchild)=");        return CountBiTreeLeaf(T->lchild) + CountBiTreeLeaf(T->rchild);     }}//统计叶子结点的个数

运行时就会出现死循环

通过死循环的部分可以看出,在判断时是不能进入结点为空的语句中的,于是从树的构建中寻找问题,最终发现这一条语句存在着问题:

if(ch == 'Z')    {        T = NULL;    }

这里给T赋值为空,也就是给整个结构体地址赋值为空,但是我们的目的是给该结构体中的内容,即左孩子的地址指向的内容赋为空,所以正确代码应为:

if(ch == 'Z')    {        *T = NULL;    }
这也是为什么在后面一直不能进入判空的语句的原因,修改后的程序运行起来是这样的:


总结:对指针的使用还是不能把握,需要多多理解。

阅读全文
0 0
原创粉丝点击