追天荧火 2019-01-04 21:56 采纳率: 100%
浏览 435
已采纳

一个非递归树的生成算法问题

以下是代码

该函数的功能是根据一个字符串生成一个二叉树,
传入的字符串是该二叉树前序遍历的结果,
'#'代表NULL,
例如:"abd#e##fg###c##".

bintree createbintree(char *s) {
    bintree stack[Maxsize];
    int top = 0;
    bintree t = (bintree)malloc(sizeof(bintnode));
    bintree p = t;
    while ((*s)!='\0')
    {
        if ((*s)!='#')
        {
            p->data = *s;
            stack[top++] = p;
            p->lchild = (bintree)malloc(sizeof(bintnode));
            p = p->lchild;
        }
        else
        {
            if(p!=NULL)
                free(p);
            if (top == 0)return t;
            p = stack[--top];
            p->rchild = (bintree)malloc(sizeof(bintnode));
            p = p->rchild;
        }
        s++;
    }
    return t;
}

图片说明
在第一次遇到#的时候,就是运行到上图所示代码的地方,
在执行完p=stack[--top]后,p的内容是这样的

图片说明

可是在执行p->rchild = (bintree)malloc(sizeof(bintnode));后

图片说明
左右孩子的地址空间一样了,这是什么造成的?

  • 写回答

1条回答

  • threenewbee 2019-01-05 00:16
    关注

    把free(p)去掉看看

    #include "stdlib.h"
    
    #define Maxsize 100
    
    typedef struct bintnode
    {
        char data;
        bintnode * lchild;
        bintnode * rchild;
    } *bintree;
    
    bintree createbintree(char *s) {
        bintree stack[Maxsize];
        int top = 0;
        bintree t = (bintree)malloc(sizeof(bintnode));
        bintree p = t;
        while ((*s) != '\0')
        {
            if ((*s) != '#')
            {
                p->data = *s;
                stack[top++] = p;
                p->lchild = (bintree)malloc(sizeof(bintnode));
                p = p->lchild;
            }
            else
            {
                if (p != NULL)
                {
                    //free(p);
                }
                if (top == 0)return t;
                p = stack[--top];
                p->rchild = (bintree)malloc(sizeof(bintnode));
                p = p->rchild;
            }
            s++;
        }
        return t;
    }
    
    int main()
    {
        char * s = "abd#e##fg###c##";
        bintree tree = createbintree(s);
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算