weixin_54541337 2023-01-02 18:35 采纳率: 50%
浏览 27
已结题

天哪,二叉树不会了.

为啥我二叉树创建好之后,传到遍历方法中,输出就不对呢
贴代码图和问题图
用c语言写的先序创建二叉树,纠结半天了。劳请各位看看

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct TreeNode{
    char data;
     struct TreeNode *lchild;
    struct TreeNode *rchild;
}TreeNode;

void pf(TreeNode *treeList){
    printf("根地址:%d\n",treeList);
    if(treeList!=NULL){
        printf("根结点:%c\n",treeList->data);
        pf(treeList->lchild);
        pf(treeList->rchild);
    }
}

TreeNode* create(TreeNode *treeList){
    char value;
    printf("请输入一个字符\n");
    scanf(" %c",&value);//注意啊,回车也会被当作一个字符 
     if(value=='#'){
        treeList=NULL;
    }else{
        treeList=(TreeNode *)malloc(sizeof(TreeNode));
        treeList->data=value;
        
        printf("输出没问题啊:%c,%d\n",treeList->data,treeList);
        create(treeList->lchild);
        create(treeList->rchild);
    }
    return treeList;
    
} 



int main(){
    TreeNode *treeList;
    treeList=(TreeNode*)malloc(sizeof(TreeNode));
    treeList->lchild=NULL;
    treeList->rchild=NULL; 
    treeList=create(treeList);
    printf("根结点:%c,%d\n",treeList->data,treeList);
    pf(&treeList);
}

img

  • 写回答

3条回答 默认 最新

  • |__WhoAmI__| 2023-01-02 18:46
    关注

    你这代码中,在遍历函数 pf 中传入了二叉树的根结点的地址,但是在打印输出时,使用了 treeList 这个指针变量本身的值,而不是它所指向的地址中的值。

    在 C 语言中,可以通过在变量前加上一个 * 号来访问指针变量所指向的内存地址中的值。

    例如可以将代码中的

    printf("根结点:%c\n",treeList->data);
    

    改为

    printf("根结点:%c\n",(*treeList).data);
    

    或者

    printf("根结点:%c\n",*treeList.data);
    

    来访问根结点中的数据。

    可以在遍历函数中对每个结点都使用类似的方法来访问它们的数据。

    另外在代码中,使用了 scanf 函数来输入字符,但是 scanf 函数会读取空格和回车符,因此在输入字符时可能会出现问题。

    可以使用 getchar 函数来输入字符,这样就可以避免上述问题了。

    例如可以将代码中的

    scanf(" %c",&value);
    

    改为

    value = getchar();
    

    来输入字符。
    仅供参考,望采纳,谢谢。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 1月10日
  • 已采纳回答 1月2日
  • 创建了问题 1月2日

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b