【问题标题】:Crash when trying to print the value at the root of a binary tree尝试在二叉树的根部打印值时崩溃
【发布时间】:2017-04-18 01:08:41
【问题描述】:

到目前为止足够简单的程序:由包含整数值的节点和指向节点左右分支的指针组成的二叉树。

#include <stdio.h>
#include <stdlib.h>

typedef struct node{
    int val;
    struct node *left;
    struct node *right;
} Node;

void insert(Node *root, int val);

int main(void){
    Node *root = NULL;

    insert(root, 5);
    insert(root, 3);

    printf("%d\n", root->val);


    return 0;
}

void insert(Node *root, int val){
    if(root == NULL){ // Create tree if root is empty
        root = malloc(sizeof(struct node));
        root->val = val;
        root->left = NULL;
        root->right = NULL;
    } else if(val < root->val){ // branch to left of tree if new value is less than root value
        if(root->left == NULL){
            root->left = malloc(sizeof(struct node));
        }

        root->left->val = val;
    } else if(val > root->val){ // branch to right of tree if new value is greater than root value
        if(root->right == NULL){
            root->right = malloc(sizeof(struct node));
        }

        root->right->val = val;
    }
}

无论出于何种原因,插入都很顺利。我可以输入 5 和 3(任意)都很好。但我无法打印出应该在 root->val 中的值“5”?该程序完全崩溃了。我是否忽略了什么?

【问题讨论】:

  • 尝试在第一个 insert() 之后打印 root 的指针值 - 这不是你想的那样......
  • 我好像搞砸了。
  • 你搞砸的一种方式是不做研究。 SO 上的所有链接列表/树帖子中约有一半存在“仅更新本地变量”问题。

标签: c binary-tree binary-search-tree


【解决方案1】:

问题出在insert的签名上:

void insert(Node *root, int val);

它不可能将NULL 用作root 参数,因为它无法将发生在函数内部的更改传回。对insert 内的root 的任何修改都保留在insert 的本地,因为指针是按值传递的,即复制

对于一个好的签名,您有两种一般选择:

  • insert返回新的root,即Node *c如果你使用这种方法,调用者需要如下调用:root = insert(root, 5);
  • 传递Node**而不是Node*,即void insert(Node **root, int val); 如果你使用这种方法,调用者将需要如下调用:insert(&amp;root, 5)。当然,insert 的实现也需要更改,因为额外的间接级别需要额外的取消引用。

【讨论】:

  • 谢谢。我似乎需要重新审视范围和记忆力。
  • 我认为你需要复习pass by value; 范围和内存看起来是正交的。
猜你喜欢
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-13
相关资源
最近更新 更多