【问题标题】:What is wrong with my operator += of the binary search tree?我的二叉搜索树的运算符 += 有什么问题?
【发布时间】:2013-11-22 06:04:35
【问题描述】:

我有一些关于二叉搜索树 (BSTreeBag) 的代码行,但我不太明白。

“operator +=(const BSTreeBag& addend)”要求将 addend 中的内容插入到我们拥有的当前树中。如果我们拥有的当前树与“addend”相同,我们需要将树加倍(以复制树中的所有项目)

这是我的代码

template <class ItemType>
void BSTreeBag<ItemType>::operator +=(const BSTreeBag& addend)
{
    if(this==&addend)//This works
    {
        binary_tree_node<ItemType>* addroot_ptr=root_ptr;//create a pointer
                                                         //that points to the current tree 
        insert_all(addroot_ptr);//This is a helper function that insert 
                                //every item of the addend into the current tree. It works fine.
    }
    else
    {
        insert_all(addend.root_ptr);
    }
}

只要不进行自赋值,代码行就可以完美运行。它总是停在这条线上

insert_all(addroot_ptr);

没有提供有关分段错误或其他问题的任何信息。有人可以解释发生了什么吗?

【问题讨论】:

  • 您知道您的操作员被声明(和定义)错误吗?它应该返回对对象实例的引用(例如*this)。
  • 另外,为什么要创建一个临时指针而不是直接传递root_ptr
  • 我想如果我使用root_ptr,它指向的对象会改变。 root_ptr 是指向根的指针。它不应该改变。
  • 另外我认为这个函数是无效的,它不需要返回任何东西。就像我说的那样,问题出在“如果”部分,其他一切正常。
  • 他们不是在做同样的事情,自我分配与否?我认为 insert_all() 有问题。

标签: c++ data-structures tree


【解决方案1】:

一个很可能的问题是,当您将一棵树添加到自身时会出现无限循环。就像在中一样,您在遍历树的同时添加节点,但由于添加了新节点,您将继续迭代并添加它们,无限循环。

让我们举一个简单列表的例子。假设您有以下列表:

根 -> A

现在,如果您尝试将列表添加到自身,则从根指针遍历列表,找到节点A,然后添加它。现在你的列表看起来像

根 -> A -> A

您继续迭代并找到...节点A(再次),然后添加它:

根 -> A -> A -> A

等等等等。

您可能应该从root_ptr 创建一个全新的树,然后添加它。

【讨论】:

  • 我明白你的意思。我做到了,它确实通过了。谢谢!
【解决方案2】:

这是我的样子(我认为说明和测试文件都有点古怪):

template <class ItemType>
void BSTreeBag<ItemType>::operator+=(const BSTreeBag& addend)
{
    if (this != &addend)  
        insert_all(addend.root_ptr);
    else
    {
        BSTreeBag<ItemType> new_bst = addend;
        insert_all(new_bst.root_ptr);
        tree_clear(new_bst.root_ptr);
    }
}    

【讨论】:

    猜你喜欢
    • 2013-11-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 2019-07-27
    相关资源
    最近更新 更多