c++ - 构建二叉搜索树时出现段错误

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

<分区>

我正在构建一个二叉搜索树,但该函数给出了段错误。我不知道问题出在哪里。

树没有构建 insertintree 中的部分无法正常工作,我已经尝试过一些方法但它没有工作

#include<bits/stdc++.h>
using namespace std;

struct node // structure of node
{
    int k;
    node* left = NULL;
    node* right = NULL;
};    
void insertintree(node* root, int key)
{
    if (root == NULL)//root addition
    {
        node* root = new node;
        root->k = key;
    }
    else 
    {
        if (root->k < key)  insertintree(root->right, key);
        else insertintree(root->left, key);
    }
}    
void inorder(node* root) 
{
    if (root != NULL) 
    {
        inorder(root->left);
        cout << root->k;
        inorder(root->right);
    }
}    
int main() 
{
    node* root = NULL;
    insertintree(root, 1);
    cout << root->k;
}

最佳答案

主要有两个问题:

  1. 您需要通过 root通过引用,否则,insertintree 将使用 root 的拷贝你通过了。

    void insertintree(node* &root, int key)
    //                     ^^^
    {
    
    }
    
  2. 其次,在您的第一个 if的正文,你重新声明了一个新的 root Node这将影响过去的那个。改为

    if (root == NULL)//root addition    
    {
         root = new node;
         root->k = key;
    }
    

同时避免使用 #include<bits/stdc++.h> 练习和 using namespace std; : 为什么?请参阅以下讨论:

关于c++ - 构建二叉搜索树时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56703015/

相关文章:

C++ 迭代器取消引用和前缀递增/递减样式? *--Iter ok 风格明智吗?

c++ - 高效/优雅的二维容器

C语言编程数组元素减法

c++ - 使用 'auto' 和 std::minmax 观察奇怪的行为

c++ - 在运行时将指针推送到 vector C++

c++ - 在 Windows 中打印时以编程方式设置每张页数 (N-Up) 选项

algorithm - 迭代合并排序的运行时间和不变量是多少?

java - 判断一个数是否是4的幂,logNum % logBase == 0 vs (logNum/logBase) % 1 == 0

c++ - 在 std::vector<std::unique_ptr<T>> 中迭代 const T&

c++ - 从指向具有可变数量参数的函数的指针映射调用函数