C++中的二叉搜索树

Binary Search Tree in C++

本文关键字:搜索树 C++      更新时间:2023-10-16

我有以下代码要插入 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"不起作用。!