2012-11-22 192 views
2

我正在爲普通的二叉樹(不搜索)創建「查找」和「刪除」功能。下面是查找功能的代碼:從二叉樹中刪除並找到一個節點

bool Find_Node(FileItem * item, Node *current) //function starts with root 
{ 
    if (current->getNameItem() == item->getName()) //getNameItem() retrieves the data name in node. 
    { 
     currentItem = current; //I have set currentItem as an attribute (pointer to a Node) in the tree class. I created it to point to the node I want to find. 
     return true; 
    } 
    Node* child [2]; 

    child[0] = current->getLeft(); 
    child[1] = current->getRight(); 

    bool res = false; 

    for (int i = 0; res == false && i < 2 ; i++) 
    { 
     if(child[i] != NULL) 
      res = Find_Node(item, child[i]); 
    } 
    return res; 
} 

有沒有更好的方法來找到節點?並可能有人請幫助我與刪除功能。

回答

2

添加NULL的基本情況以使邏輯簡單。

bool Find_Node(FileItem * item, Node *current) 
{ 
    if(current == NULL) return false; 
    if (current->getNameItem() == item->getName()) { 
     currentItem = current; 
     return true; 
    } 
    return Find_Node(current->getLeft()) || Find_Node(current->getRight()); 
} 

void Delete_Node(Node*& current) 
{ 
    if(current == NULL) return; 
    Delete_Node(current->getRight()); 
    Delete_Node(current->getLeft()); 
    delete current; 
    current = NULL; 
} 

如果我能看到節點的實現,我可以告訴你如何實現swap功能,你需要

如果樹是非常大的,這可能會導致一個計算器。但是,通過將解決方案從遞歸方式更改爲迭代方案可以解決該問題。

+0

感謝您的快速回復。那麼刪除功能呢? –

+0

@MohamadOmarHindi我困惑了一秒。我現在重新閱讀這個問題並且清楚。你可以改變'Node'類的實現嗎?添加一個交換方法真的有助於刪除。 – andre

+0

是的,我可以。對不起,我沒有足夠的解釋。如果我想要刪除的I節點有孩子,他們也必須刪除,所以不需要交換。 –