我正在创建一个二叉搜索树,这是我的TreeDB.cpp文件的代码:
TreeDB::TreeDB()
{
root = NULL;
}
bool TreeDB::insert(DBentry * _entry)
{
if (root == NULL)
{
root = new TreeNode(_entry);
root->setLeft(NULL);
root->setRight(NULL);
cout <<"Inserted at root";
}
else
{
insert_helper(root,_entry);
}
}
bool TreeDB::insert_helper(TreeNode *curr, DBentry * _entry)
{
string temp1 = curr->getEntry()->getName();
string temp2 = _entry-> getName();
if(temp1 == temp2)
{
cout <<"Error: entry already exists"<<endl;
delete _entry;
return false;
}
else if(temp1<temp2)
{
if(curr->getRight() == NULL)
{
curr->setRight(new TreeNode(_entry));
cout << "Set right";
return true;
}
else
{
insert_helper(curr->getRight(),_entry);
}
}
else
{
if(curr->getLeft() == NULL)
{
curr->setLeft(new TreeNode(_entry));
cout <<"Set Left";
return true;
}
else
{
insert_helper(curr->getLeft(),_entry);
}
}
}
我的头文件是Tree.h:
class TreeDB {
private:
TreeNode* root;
int probesCount;
public:
TreeDB();
~TreeDB();
bool insert(DBentry* newEntry);
bool insert_helper(TreeNode*curr,DBentry*_entry);
};
我也在这样创建这个树的对象:
TreeDB Tree;
while (!lineStream.eof())
{
if (command == "insert")
{
unsigned int address;
string name;
bool active;
lineStream >> name >> address >> active;
DBentry * a = new DBentry(name,address,active);
Tree.insert(a);
}
但是,每次我尝试插入某些东西时,它总是在根处插入,因此前一个永远不会被保存或者在每次插入后被删除。关于如何解决这个问题的任何提示?