2

通常のバイナリ ツリー (検索ではない) の「検​​索」および「削除」機能の作成に取り組んでいます。以下は、find 関数のコードです。

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

ノードを見つけるためのより良い方法はありますか? 誰かが削除機能を手伝ってくれるかもしれません。

4

1 に答える 1

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

Node の実装を見ることができれば、swap必要な機能を実装する方法を教えてくれるでしょう

ツリーが非常に大きい場合、スタック オーバーフローが発生する可能性があります。しかし、その問題は、ソリューションを再帰的なものから反復的なものに変更することで解決できます。

于 2012-11-22T20:30:17.973 に答える