[英]What is wrong with my binary search tree insertion logic?
二进制搜索.h:
#ifndef BST_BINARYSEARCH_H #define BST_BINARYSEARCH_H struct Node{ int value; Node* left; Node* right; }; class BST{ public: Node* root; BST(){ root = nullptr; } Node* insertNode(Node* root, Node toInsert); void inOrder(Node* root); }; #endif //BST_BINARYSEARCH_H
二进制搜索.cpp:
#include #include #include "binarysearch.h" Node* BST::insertNode(Node* root, Node toInsert) { if(root == nullptr){ root = &toInsert; } else { if (toInsert.value value) root->left = insertNode(root->left, toInsert); else root->right = insertNode(root->right, toInsert); } return root; } void BST::inOrder(Node *root) { if(root!= NULL){ inOrder(root->left); std::coutvalue; inOrder(root->right); } }
主.cpp:
#include #include "binarysearch.h" int main() { BST bst; Node* root = nullptr; Node a; a.value = 4; a.left = NULL; a.right = NULL; root = bst.insertNode(root, a); bst.insertNode(root, a); a.value = 5; bst.insertNode(root, a); a.value = 6; bst.insertNode(root, a); a.value = 7; bst.insertNode(root, a); a.value = 8; bst.insertNode(root, a); bst.inOrder(root); return 0; }
显然,当我插入更多项目时,我的根不断从原始位置移动。
我正在 bst.inOrder(root) 上以退出代码 139(被信号 11:SIGSEGV 中断)完成 Process。
这里有什么问题?
问题在于插入节点功能,这里你说如果树是空的,我们将根设置为“toInsert”的地址。 这里的问题是 toInsert 不是引用,它是通过副本传递的。 这意味着 toInsert 是一个临时的本地副本变量,一旦函数结束它就会过期。 这意味着您的根指针现在不指向任何内容。
//NOTE: Passing toInsert, copy is made
Node* BST::insertNode(Node* root, Node toInsert) {
//NOTE: root is null, so we set it to point to the node's copy
if(root == nullptr){
root = &toInsert;
}
//NOTE: The copy is destroyed because we ran out of scope
}
解决方案是使“toInsert”成为指针或引用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.