c++ - 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;
}
解决方案
您正在按值传递参数
Node* insert(Node* root, int data) {
root
是bst.root
. root = new Node(data);
分配给副本,而不是原始变量。您可以使用参考:
Node* insert(Node*& root, int data) {
推荐阅读
- javascript - 在 typeahead 输入框中添加图标
- outlook - Outlook API - 使用数据获取 Webhook 通知
- python - Pandas:在单个操作中从单个系列创建两个列表
- installation - 由于 WiX 安装,添加显示 HTML 页面
- python - 在 Web 应用程序中加载大尺寸模型文件
- jboss - 哪个版本的 jboss EAP 支持 IBM MQ 9.0.0.5?
- javascript - event.preventDefault() 在一种情况下有效,但在其他情况下无效
- amazon-web-services - 在 EC2 实例上使用 API 托管后端应用程序
- django - 我们如何在 django 中为 jwt 令牌中的不同用户分配不同的到期时间
- python - 在python中绘制一个大矩阵