追天荧火 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 如何实验stm32主通道和互补通道独立输出
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题