首页 > 解决方案 > C++中的二叉搜索树插入方法

问题描述

我的任务是从头开始为 C++ 中的二叉搜索树创建插入方法。当我在 Visual Studio 中运行它时,我根本没有得到任何输出,它以代码 0 退出。似乎插入函数的 else if 和 else 块永远不会运行,我不知道为什么。任何帮助将不胜感激,在此先感谢!

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

标签: c++data-structuresinsertbinary-treebinary-search-tree

解决方案


您正在按值传递参数

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

rootbst.root. root = new Node(data);分配给副本,而不是原始变量。您可以使用参考:

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

推荐阅读