【发布时间】:2020-04-18 08:54:43
【问题描述】:
我目前正在学习 c++,为了学习它,我将实现一个简单的二叉搜索树类,以便掌握 c++ 中的概念。在实现 add 函数时,我收到一个有趣的错误,其中似乎程序无法将节点识别为 null,然后立即崩溃,因为节点应该为 null。
//Here is my add/insert function I created.
void BinarySearchTree::insert(double x){
if(root == NULL){
root = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->val = x;
return;
}
bool inserted = false;
struct TreeNode* curr = root;
while(curr != NULL && !inserted){
if(curr->val == x){
return;
}
if(x > curr->val){
if(curr->right == NULL){
curr->right = (struct TreeNode*) malloc(sizeof(struct TreeNode));
curr->right->val = x;
inserted = true;
} else {
curr = curr->right;
}
} else {
if(curr->left == NULL){
curr->left = (struct TreeNode*) malloc(sizeof(struct TreeNode));
curr->left->val = x;
inserted = true;
} else {
curr = curr->left;
}
}
}
}
//This is the TreeNode struct and the BinarSearchTree class in my header file if it helps
struct TreeNode{
double val;
struct TreeNode *right;
struct TreeNode *left;
};
class BinarySearchTree{
private:
struct TreeNode *root;
public:
void insert(double x);
};
【问题讨论】:
-
您需要解决您的问题,以便显示的代码满足minimal reproducible example 的所有要求,如help center 中所述,否则任何人都不太可能为您提供帮助。虽然我确实在显示的代码中看到了一些几乎确定的错误,但除非可以证明,否则不能确定,这只能通过minimal reproducible example 来完成。
-
struct关键字仅在您实际定义结构时在 C++ 中是必需的。其他时候,这是不必要的。 -
-
只是一种预感,可能与
left和right似乎没有被初始化有关。您可能想为TreeNode创建一个构造函数并将它们设置为nullptr。 -
是的,显示的代码无法初始化
left和right。这就是崩溃的原因。出于某种原因,它还使用 C 库的malloc,而不是 C++ 的new。最后,insert()是不必要的复杂和过度设计。insert()的经典递归实现要简单得多;它应该是,也许,十行左右的代码。 “你对管道的考虑越多,就越容易堵住排水管”——《星际迷航 III》中的斯科蒂。
标签: c++ xcode class struct binary-search-tree