algorithm - 使用 void 函数的二叉搜索树插入

标签 algorithm c++11 data-structures binary-search-tree

我已经编写了两种不同的代码来插入二叉树,一种有效而另一种无效。

这是我的节点的样子:

struct node
{
    int data;
    node *left;
    node *right;
};

下面是node* newnode(int a)的代码

node* newnode(int a)
{
    node *temp=new node;
    temp->data=a;
    temp->left=nullptr;
    temp->right=nullptr;
    return temp;
}

下面是两种不同的插入代码:

这个返回一个指向节点的指针:

 node* insertion(node *root, int a)
 {
    if(root==nullptr)
        return newnode(a);
    else if(a<root->data)
        root->left=insertion(root->left, a);
    else
        root->right=insertion(root->right, a);
 }

这个返回无效:

void insertion2(node *root,int a)
{
    if(root==nullptr)
        root=newnode(a);
    else if(a<root->data)
        insertion2(root->left,a);
    else
        insertion2(root->right,a);
}

返回 void 的那个不起作用。根据我所做的分析,在函数调用之后,root 仍然是 nullptr。谁能解释一下为什么它不起作用?

最佳答案

请注意,在 insertion 版本中,您有 root->left = insertion(root->left, a)root->right = insertion( root->right, a),但是在 insertion2 中没有任何相同的效果。实际上,insertion2 除了泄漏内存什么都不做。

关于algorithm - 使用 void 函数的二叉搜索树插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44565455/

相关文章:

c - 将十六进制字符串表示形式解析为整数

c# - 如何合并连续的时间段?

c++ - 如何正确调用模板函数?

c++ - 没有重复的链表

algorithm - 打印到达第 n 个楼梯的方法

algorithm - (n 选择 k) 和长度为 n 的位串之间的双射,其中设置了 k 位

java - Java 中 ArrayList 的 add() 方法背后的算法是什么?

c++ - g++:用闭包类型初始化的 std::function 总是使用堆分配?

c++ - 更好的做法 : Ever looping thread or successive threads?

c++ - 反向链表导致循环