简体   繁体   中英

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. 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 .

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

void insertNode(int data, Node*& node)

Also, you don't need to check for head == nullptr in insert. You have a duplicate check in insertNode

So insert could look like this:

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

Finally, you're not initializing head within the constructor. It's possible that head will be initialized to something other than nullptr, especially if you compile this in release mode. 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.

insertNode() takes a copy of the pointer, so changes made inside the function have no effect on the actual pointer in the tree. 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”不起作用。!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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