c++ - Node* 与 main 中的 Node

标签 c++ tree binary-search-tree

我正在编写一个二叉搜索树。

class Node {
 public:
  Node* left;
  Node* right;
  int data;

  Node(int x) : data(x) {}

  void insert(int value) {
    if (value < data) {
      if (left == NULL)
        left = new Node(value);
      else
        left->insert(value);
    } else {
      if (right == NULL)
        right = new Node(value);
      else
        right->insert(value);
    }
  }

  bool contains(int value) {
    if (value == data)
      return true;
    else if (value < data) {
      if (left == NULL)
        return false;
      else
        return left->contains(value);
    } else {
      if (right == NULL)
        return false;
      else
        return right->contains(value);
    }
  }
};

当我在主程序中使用 Node x 然后调用 x.insert(15) 时,它给出了一个段错误。如果我使用 Node* x=new Node(10) 然后使用 use x->insert(15) 然后它工作正常。这背后的原因是什么?

int main() {
  Node x(10);
  x.insert(15);
}

最佳答案

主要问题是您没有使用 nullptr 初始化指针(leftright),但您假设它们是使用insert 中的空指针。在构造函数中进行初始化可以解决问题:

Node(int x) : data{x}, left{nullptr}, right{nullptr} {}

关于c++ - Node* 与 main 中的 Node,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58351457/

相关文章:

java - 在java中打印BST中的所有路径

C++ 字符串数组,从文件中加载文本行

data-structures - 什么是 Root过的树?

data-structures - 树是有向图还是无向图?

R gbm 为什么 fit$trees 的长度总是数据集 iris 的 n.trees 的 3 倍

c++ - 二叉搜索树中的搜索函数实现

c++ - 访问多 channel OpenCV Mat 中的元素

c++ - 使用现有的 cpp 核心代码构建 Web 应用程序

c++ - opencv c++ 垫到 vector <关键点>

data-structures - 多次使用相同 key 的红黑树 : store collections in the nodes or store them as multiple nodes?