簡體   English   中英

我的二元搜索樹的運算符+ =有什么問題?

[英]What is wrong with my operator += of the binary search tree?

我有一些關於二進制搜索樹(BSTreeBag)的代碼行,我不太清楚。

“運算符+ =(const BSTreeBag&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);

沒有提供任何有關細分錯誤或其他問題的信息。 有人可以解釋發生了什么嗎?

一個很可能的問題是,當您向其添加一棵樹時會出現無限循環。 像在其中一樣,您在遍歷樹時添加節點,但是由於要添加新節點,因此您將繼續迭代並添加它們,這是無限的。

讓我們舉一個簡單的例子。 假設您有以下列表:

root -> A

現在,如果您嘗試將列表添加到自身,則從根指針遍歷該列表,找到節點A ,然后進行添加。 現在您的清單看起來像

root -> A -> A

您繼續迭代並再次找到...節點A ,然后將其添加:

root -> A -> A -> A

等等等等。

您可能應該從root_ptr創建一個全新的樹,然后添加它。

這是我的樣子(我認為指令和測試文件都有些古怪):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM