简体   繁体   English

C++中的二叉搜索树

[英]Binary Search Tree in C++

I have the following code to insert in the bst however, it fails to insert all the nodes except for the root.我有以下代码要插入到 bst 中,但是它无法插入除根之外的所有节点。 Any idea what I am doing wrong?知道我做错了什么吗?

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);
        }
    }
};

The parameter head in insertNode shadows the member variable named head . insertNode 中的参数head隐藏名为head的成员变量。

However, while that's a really bad practice, the other answer is the true reason for your error, so please select his answer instead (once you get it working, of course).然而,虽然这是一个非常糟糕的做法,但另一个答案是你错误的真正原因,所以请选择他的答案(当然,一旦你开始工作)。

I'd recommend changing the signature of insertNode to我建议将insertNode的签名insertNode

void insertNode(int data, Node*& node)

Also, you don't need to check for head == nullptr in insert.此外,您不需要在插入中检查head == nullptr You have a duplicate check in insertNode您在insertNode有重复的检查

So insert could look like this:所以插入看起来像这样:

void insert(data) {
    insertNode(data, head);
}

Finally, you're not initializing head within the constructor.最后,您没有在构造函数中初始化 head 。 It's possible that head will be initialized to something other than nullptr, especially if you compile this in release mode. head 可能会被初始化为 nullptr 以外的其他内容,特别是如果您在发布模式下编译它。 Add a constructor like this:添加一个像这样的构造函数:

BST() : head(nullptr) {
    // Other init stuff here if necessary
}

You'll also want to make Node* head a private data member instead of public.您还需要使Node* head成为私有数据成员而不是公共数据成员。

insertNode() takes a copy of the pointer, so changes made inside the function have no effect on the actual pointer in the tree. insertNode()获取指针的副本,因此在函数内部所做的更改对树中的实际指针没有影响。 What you want to do is take a reference to the pointer:你想要做的是引用指针:

void insertNode(int data, Node*& head)

在您的函数“insertNode”中,您正在使用 if(head) ,此 if 仅在 head == 1 时才起作用,并且 head 永远不会等于 1 因为它是一个指针,所以这个“if”不起作用。!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM