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日

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度