【问题标题】:How to add a node in BST?如何在 BST 中添加节点?
【发布时间】:2017-10-12 04:26:33
【问题描述】:

我使用递归尝试了以下算法,但节点没有附加到树上。请告诉我有什么问题。

void search_add(struct node *t)
{
    if(t==NULL)
    {
        t = newNode(temp->key);
        return;
    }
    else if(t->key>temp->key)
    {
        search_add(t->right);
    }
    else if (t->key<temp->key)
    {
        search_add(t->left);
    }
}

void insert(struct node *node, int key)
{
    temp = newNode(key);
    search_add(node);
}

int main(void)
{
    root = newNode(50); 
    insert(root,30);

    return 0;
}

【问题讨论】:

  • t = newNode(temp-&gt;key); 只是更改传递的本地副本,然后被遗忘,调用者的t-&gt;rightt-&gt;left 仍然是NULL
  • 此网站上有 数千个 重复此问题。不幸的是,错误通常是由初学者犯的,问题的标题/文本如此不同,他们很难真正找到。 t = newNode(temp-&gt;key); 对传入的 调用者 参数执行 nothing。就函数而言,它是一个局部变量。所有这些最终都会导致内存泄漏。 Example duplicate here.
  • 欢迎来到 StackOverflow。请采取tour,学习提出好问题stackoverflow.com/help/how-to-ask,制作minimal reproducible example。如果您正在寻求有关调试代码的帮助,请参阅ericlippert.com/2014/03/05/how-to-debug-small-programs
  • temp 是一个全局变量。
  • @WhozCraig,我该如何解决?

标签: c pointers recursion data-structures binary-search-tree


【解决方案1】:

正如Weather Vave 所述,问题是:

t = newNode(temp-&gt;key); 只是更改传递的本地副本, 然后忘记了,调用者的t-&gt;rightt-&gt;left 仍然为 NULL。

一个解决方案可能是改变这个:

void search_add(struct node *t)

到这里:

void search_add(struct node *t)

当然,然后在函数体内使用*t,而不是t

这样你传递了一个双指针,这将使更改在函数范围之外可见。

【讨论】:

    【解决方案2】:

    你没有在你的递归中分配任何值。请尝试下面的代码我是一个 java 所以请忽略任何语法问题。

    /* If the tree is empty, return a new node */
        if (node == NULL) return newNode(key);
    
        /* Otherwise, recur down the tree */
        if (key < node->key)
            node->left  = insert(node->left, key);
        else if (key > node->key)
            node->right = insert(node->right, key);   
    
        /* return the (unchanged) node pointer */
        return node; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      • 2016-11-11
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 2021-05-24
      相关资源
      最近更新 更多