【发布时间】: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