[英]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) {
root
是bst.root
的副本。 root = new Node(data);
分配給副本,而不是原始變量。 您可以使用參考:
Node* insert(Node*& root, int data) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.