【发布时间】:2014-04-16 09:14:12
【问题描述】:
我正在尝试使用递归在 c++ 中实现 BST。然而,我发现自己陷入了两难境地。
在插入函数中,我使用引用TreeNode *&node来传递函数参数。我不想引用 const,因为我需要在 Insert 函数中更改节点。另一方面,当我调用像tree.Insert(10, tree.Getroot()) 这样的函数时,会发生错误,因为函数Getroot 创建了不能分配给非常量引用的临时变量。而且我知道我可以通过将TreeNode *rootpublic 轻松修复它,但我不想这样做。
我应该怎么做才能修复它或者有更好的设计吗?请帮忙,提前谢谢。 这是头文件。
#ifndef BINARY_SEARCH_TREE_H
#define BINARY_SEARCH_TREE_H
class TreeNode
{
public:
TreeNode(int x = 0,TreeNode* l = nullptr, TreeNode* r = nullptr)
: element(x), left(l), right(r) { }
int element;
TreeNode* left;
TreeNode* right;
};
class BST
{
public:
BST(TreeNode *t = nullptr) : root(t) {}
void Insert(int x, TreeNode*& node)
{
if (node == nullptr) {
node = new TreeNode(x, nullptr, nullptr);
if (node == nullptr)
std::cout << "Insert Failure" << std::endl;
}
else if (node->element < x) {
Insert(x, node->right); //easy to make a mistake
}
else if (node->element > x) {
Insert(x, node->left);
}
}
TreeNode *Getroot()
{
return root;
}
private:
TreeNode* root;
};
#endif
【问题讨论】:
-
树不应在公共接口中公开其节点类型 - 使其对树私有。公共函数应该是
void Insert(int x);,而GetRoot根本不应该存在。一旦隐藏了实现细节,很多问题就会消失。 -
如果指针为空指针,您可能知道您的 Insert 不会插入任何内容。请重新考虑您的设计
标签: c++ insert constants binary-search-tree