C++中的二叉搜索树
Binary Search Tree in C++
我有以下代码要插入 bst 中,但是,它无法插入除根之外的所有节点。知道我做错了什么吗?
class Node
{
public:
int data;
Node* right;
Node* left;
Node(int data)
{
this->data = data;
}
Node() {}
};
class BST
{
public:
Node* head;
void insert(int data)
{
if (head == nullptr)
{
head = new Node(data);
head->data = data;
}
else
{
// head = new Node(data);
insertNode(data, head);
}
}
void insertNode(int data, Node* head)
{
if (head == nullptr)
{
head = new Node(data);
return;
}
if (head)
{
Node* temp = head;
if (temp->data > data)
{
insertNode(data, temp->left);
}
else if (temp->data <= data)
insertNode(data, temp->right);
}
}
};
insertNode 中head
的参数隐藏名为 head
的成员变量。
然而,虽然这是一个非常糟糕的做法,但另一个答案是你错误的真正原因,所以请选择他的答案(当然,一旦你让它工作)。
我建议将insertNode
的签名更改为
void insertNode(int data, Node*& node)
此外,您无需检查插入中的head == nullptr
。 您有重复的签入insertNode
所以插入可能看起来像这样:
void insert(data) {
insertNode(data, head);
}
最后,您不会在构造函数中初始化 head。 head 可能会初始化为 nullptr 以外的内容,尤其是在发布模式下编译它时。 添加如下所示的构造函数:
BST() : head(nullptr) {
// Other init stuff here if necessary
}
您还需要将Node* head
设为私有数据成员,而不是公共数据成员。
>insertNode()
获取指针的副本,因此在函数内部所做的更改对树中的实际指针没有影响。您要做的是引用指针:
void insertNode(int data, Node*& head)
在你的函数"insertNode"中,你正在使用 if(head),这个 if 只有在 head == 1 时才有效,并且 head 永远不会等于 1,因为它是一个指针,所以这个"if"不起作用。!
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 正在尝试重载二进制搜索树分配运算符
- 使用C++创建特殊的二叉搜索树
- 在递归二叉搜索树中搜索
- 在二叉搜索树中插入时出现分段错误
- C++二叉搜索树模板从函数返回节点
- 我可以在没有堆栈的情况下在二叉搜索树中实现迭代器吗?
- 在二叉搜索树C++中计算平均值
- 在字符串的二叉搜索树中搜索子字符串 - C++
- 在二叉搜索树中插入新元素
- 如何打印在二叉搜索树中找到的数据?
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 这是一个二叉搜索树吗?黑客排名问题
- 二叉搜索树 - 实现"search"函数
- 二叉搜索树的 C++ 实现中的EXC_BAD_ACCESS错误
- 删除二叉搜索树 (C++) 中的单个元素
- 将值存储在带有C++的二叉搜索树中
- 二叉搜索树未将插入值加载到树中
- 二叉搜索树使用最常用的节点来打印出某些语句
- 如何以特定格式C++打印二叉搜索树