嘿所以我试图写一个BST,但是我遇到了很多错误,而且我很不知所措,并且不知所措。你们可以看看并指出任何关闭的东西。老师在解释任何事情时都没有用。
.h文件中的标题
class Tree
{
public:
bool insert(int k, string s);
private:
struct Node
{
int key;
string data;
Node *left;
Node *right;
};
Node* root;
bool insert(Node *& root, int k, string s);
};
.cpp文件
bool Tree::insert(int k, string s)
{
return insert(root, k, s);
}
bool Tree::insert (Node *& root, int k, string s)
{
if (root == NULL){
root = new Node;
root->key = k;
root->data = s;
root->left = NULL;
root->right = NULL;
}
else if (root == k)
return false;
else if (root->key < k)
insert (root ->left, k);
else
insert (root -> right, k);
}
答案 0 :(得分:2)
首先,代码末尾有一个缺少的括号。
答案 1 :(得分:2)
您似乎有很多未经测试的代码。您必须逐个使用这些功能。
此外,我至少看到了一个重复工作的实例。 preOrder
和postOrder
方法应该是同一算法的略微变化,但一个是基于循环的,另一个是函数递归。
将这些源文件放在一边,创建一个新项目,并一次复制粘贴到一个功能。在继续下一个功能之前进行彻底测试。如果您到达的功能可能已经在现有代码中潜伏,请不要从旧代码中复制粘贴,而是利用现有的测试代码。
看起来它应该有效。如果您需要,可以采用以下几种风格批评:v)。
Node
结构应该有自己的构造函数。始终提供构造函数以帮助确保没有任何内容处于无效状态。root
时,需要将NULL
设置为Tree
。root
参数的值不是好的样式。乍一看,left
和right
似乎永远不会收到非NULL
值。我个人赞成这里指针指针,但有些人可能会同意你的实现。答案 2 :(得分:1)
没有看实际的实现,有很多与界面相关的陷阱。以下是其中一些:
Tree::findKey
方法接受字符串作为非常量引用,为什么?Tree::insert
接受字符串值,这涉及不必要的复制,为什么?preOrder
和levelOrder
需要指向函数的指针。如果我想调用类方法或传递其他参数怎么办?我会说你最好使用谓词,或boost::function
。const
修饰符)。例如,isEmpty ()
方法。makeCopy
方法不是exception-safe。size_t
。希望它有所帮助。
答案 3 :(得分:1)
写你的第一个BST可能很难......根据Potatoswatter的建议,我首先要确保你在去其他地方之前有一个非常坚固的插入功能。因此,您可以为BST创建类,包括函数的声明,但在其定义中,只需将它们设为空函数,例如:
在您的标头文件中:
class BST
{
public:
BST();
bool insert(int k, const string& s);
bool findKey(int k, string& s);
int maxKey();
/* ... the rest of your class ...*/
};
在你的.cpp文件中:
#include "BST.h"
BST::BST()
{
/*initialize anything required for your insert function to work*/
}
//pass in a const reference for your string argument,
//or else you could end up doing a lot
//of extra processing creating a new copy of your string on the stack for
//each insertion call
bool BST::insert(int k, const string& s)
{
/* write your insertion algorithm implementation */
}
//make the rest of your function definitions that don't
//apply to insertion empty so you can compile and test your insertion algorithm
//without adding more cruft
bool BST::findKey(int k, string& s) {}
int BST::maxKey() {}
/* continue process for the rest of the class */
现在使用这种方法,您可以进行测试以确保正确地将节点插入树中而不会崩溃等,一旦完成,您可以测试是否可以找到您插入的节点。之后,您可以完成其他函数的定义,这些函数负责删除,迭代等。但是,对于每个阶段不需要的函数,将定义留空,您可以正确地构建解决方案乱七八糟的编译器错误和其他非相关项目使您无法构建手头任务的实际界面。换句话说,您无法在没有问题的情况下从树中找到或删除没有正确插入节点的节点,因此您不希望在这些步骤中绕过这些步骤。 '没有迈出第一步。您也可以在实现后续步骤时找到,例如查找节点,仍然存在插入问题...如果您只实现了插入和查找节点的完整定义,那么这些是您唯一的两个函数。我不得不担心修理。
因此将其分解为基本部分(插入,查找,删除,然后是其他所有内容),您将完成工作: - )