我正在编写一个二叉搜索树。
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
初始化指针(left
和 right
),但您假设它们是使用insert
中的空指针。在构造函数中进行初始化可以解决问题:
Node(int x) : data{x}, left{nullptr}, right{nullptr} {}
关于c++ - Node* 与 main 中的 Node,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58351457/