简体   繁体   中英

Binary Search Tree Insert Method in C++

I've been tasked with creating an insert method for a Binary Search Tree in C++ from scratch. When I run this in Visual Studio I get no output at all and it exits with code 0. It would seem the else if and else blocks of the insert function are never being run, and I can't figure out why. Any help would be much appreciated, thanks in advance!

#include <iostream>

using std::endl;
using std::cout;

class Node {
public:
    int data;
    Node* left;
    Node* right;
    Node(int data) {
        this->data = data;
        this->left = nullptr;
        this->right = nullptr;
    }
};

class BinarySearchTree {
public:
    Node* root = nullptr;

    Node* insert(Node* root, int data) {
        if (root == nullptr) {
            root = new Node(data);
        }
        else if (data <= root->data) {
            cout << "going left" << endl;
            root->left = insert(root->left, data);
        }
        else {
            cout << "going left" << endl;
            root->right = insert(root->right, data);
        }
        return root;
    }
};

int main() {
    BinarySearchTree bst;

    bst.insert(bst.root, 9);
    bst.insert(bst.root, 4);
    bst.insert(bst.root, 6);
    bst.insert(bst.root, 16);

    return 0;
}

You're passing the arguments by value in

 Node* insert(Node* root, int data) {

root is a copy of bst.root . root = new Node(data); assigns to the copy, not to the original variable. You could use a reference:

Node* insert(Node*& root, int data) {

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