【问题标题】:Binary Search Tree Insert Method in C++C++中的二叉搜索树插入方法
【发布时间】:2021-05-10 11:08:56
【问题描述】:

我的任务是从头开始为 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;
}

【问题讨论】:

  • 您是否尝试过使用调试器单步执行您的代码?为int main 设置断点,启动程序,单步执行调用bst.insert(bst.root, 9);,单步执行,...
  • 如果值相同,你不应该使用 data data 而不是 data data需要创建一个新节点

标签: c++ data-structures insert binary-tree binary-search-tree


【解决方案1】:

您正在按值传递参数

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

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

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

【讨论】:

    猜你喜欢
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多