【发布时间】:2016-09-09 18:48:05
【问题描述】:
我正在尝试构建一个插入二叉搜索树的函数,但我很难弄清楚为什么它不起作用。我从根本上理解该函数应该如何工作,但根据给我的模板,我似乎要避免创建 BST 类,而是依赖 Node 类并构建所需的函数来处理它。这是给定的模板:
#include <iostream>
#include <cstddef>
using std::cout;
using std::endl;
class Node {
int value;
public:
Node* left; // left child
Node* right; // right child
Node* p; // parent
Node(int data) {
value = data;
left = NULL;
right = NULL;
p = NULL;
}
~Node() {
}
int d() {
return value;
}
void print() {
std::cout << value << std::endl;
}
};
function insert(Node *insert_node, Node *tree_root){
//Your code here
}
我遇到的问题是当我实现以下代码时,其中 getValue 是 Node 的简单 getter 方法:
int main(int argc, const char * argv[]) {
Node* root = NULL;
Node* a = new Node(2);
insert(a, root);
}
void insert(Node *insert_node, Node *tree_root){
if (tree_root == NULL)
tree_root = new Node(insert_node->getValue());
代码似乎编译和运行没有错误,但如果我在此之后对 root 运行另一个检查,它返回 NULL。知道我在这里缺少什么吗?为什么不将root替换为与insert_node相等的新节点?
我也意识到这似乎不是实现 BST 的最佳方式,但我正在尝试使用给我的模板。任何建议将不胜感激。
【问题讨论】:
-
搜索并阅读在 c++ 中通过引用传递参数。
-
void insert(Node *insert_node, Node*& tree_root). -
更好
void insert(std::unique_ptr<Node> insert_node, std::unique_ptr<Node>& tree_root)。 -
@Jarod42,感谢您的意见!是什么让第二个版本变得更好?
-
智能指针允许不手动处理内存。因此,在您使用
std::unique_ptr的示例中,您不会有内存泄漏。
标签: c++ binary-tree