【问题标题】:C - Binary Search Tree's Initial Insertion is NULLC - 二叉搜索树的初始插入为 NULL
【发布时间】:2015-01-13 21:22:23
【问题描述】:

我写了这个二叉搜索树数据结构,但我似乎无法弄清楚为什么或如何打印的第一个节点是零 (0)。

我的代码是 ideone 上的publicly accessible here

void insert_tree(tree **l, int x, tree *parent)
{
    tree *p;       /* temp pointer */

    if (*l == NULL) {
        p = malloc(sizeof(tree));
        p->item = x;
        p->left = p->right = NULL;
        p->parent = parent;
        *l = p;     /* link into parent's record */
        return;
    }

    if (x < (*l)->item)
        insert_tree(&((*l)->left), x, *l);
    else
        insert_tree(&((*l)->right), x, *l);
}

我认为我的困惑在于指针(和指向指针的指针)的间接和使用。我知道还有其他方法可以解决这个问题,但我有充分的理由尝试坚持使用指针的这种特殊用途。

【问题讨论】:

  • 在你的代码中(第 69 行),你没有做任何事情来初始化根节点,它是一块未初始化的内存
  • 如果x == (*l)-&gt;item 会发生什么?

标签: c algorithm binary-tree


【解决方案1】:

您的代码中的问题是您在main 中添加了一个空节点,而没有初始化它的itemleftright:当您这样做时

tree *root = malloc(sizeof(tree));

root 被分配了一块未初始化的内存。您可以直接将第一个元素放入第一个元素中,但这不是必需的:您的插入代码已经处理了rootNULL 的情况。

当您更改代码以将root 分配为NULL 时,像这样,

tree *root = NULL;

您的程序运行正常 (demo)。

【讨论】:

    猜你喜欢
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多