繁体   English   中英

C++中的二叉搜索树插入方法

[英]Binary Search Tree Insert Method in C++

我的任务是从头开始为 C++ 中的二叉搜索树创建插入方法。 当我在 Visual Studio 中运行它时,我根本没有 output 并且它以代码 0 退出。似乎插入 function 的 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;
}

您通过值传递 arguments

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

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

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

暂无
暂无

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

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