Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C+中的二叉搜索树问题+;_C++_Binary Search Tree - Fatal编程技术网

C++ C+中的二叉搜索树问题+;

C++ C+中的二叉搜索树问题+;,c++,binary-search-tree,C++,Binary Search Tree,我正在创建一个二进制搜索树,下面是我的TreeDB.cpp文件代码: TreeDB::TreeDB() { root = NULL; } bool TreeDB::insert(DBentry * _entry) { if (root == NULL) { root = new TreeNode(_entry); root->setLeft(NULL); root->setRight(NULL);

我正在创建一个二进制搜索树,下面是我的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);
     }
 }
}
我还在主要创建这棵树的对象,如下所示:

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);
    }

但是,每次我尝试插入某个内容时,它总是在根目录下插入,因此前一个永远不会保存,或者在每次插入后删除。关于如何解决此问题的任何提示?

请看这个示例,如果您不知道调试器,请使用printf调试代码。您正在尝试跟踪错误插入的代码路径。一旦你看到它在哪里坏了,你就非常接近修复它了。程序还没有完成,无法重现问题。根据代码,它似乎不应该总是在根目录下插入:您试图使用什么输入来运行它?我假设您在同一次运行中输入多个值?另外,不要使用
eof()
测试输入是否有效:您需要在输入后进行测试,例如:
if(lineStram>>name>>address>>active){…}
实际上,程序总是有未定义的行为:您声明了要返回
bool
的函数,但通常不返回任何内容;你有时会退回一些东西,但这还不够好。
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);
    }