簡體   English   中英

C ++二叉樹:返回節點的后代數目。 葉子有零。 如果找不到TreeData,則返回-1

[英]C++ Binary Tree: Return the number of descendants of a node. A leaf has zero. Return -1 if the TreeData is not found

返回在樹中存儲字符的節點的后代數目。 葉子的后代為零。 如果找不到TreeData,則返回-1。 我有一個方法可以找到我們要開始的節點。 如果它不在樹中,它將返回-1。 然后,從該節點開始,我需要計算后代的數量,並且陷入困境。 到目前為止,這就是我所擁有的。

int BSTree::descendants(const TreeData &item) const
{
    Node* foundNode; // pointer to the node we're looking for
    if(!(findNode(item, root, foundNode)))
    {
        return -1; // return -1 if not found
    }
    else
    {
        return descendants(foundNode);
    }
}

int BSTree::descendants(Node *root) const
{
    if(root->left == NULL && root->right == NULL)
    {
        return 0;
    }
    // Need more here

}

// helper method that finds the node we are looking for to start counting
// descendants from and stores it to foundNode
bool BSTree::findNode(const TreeData &item, Node *root, Node *&foundNode) const
{
    if(root == NULL)
    {
        return false;
    }
    else if(item == *root->item)
    {
        foundNode = root;
        return true;
    }
    else if(item < *root->item)
    {
        findNode(item, root->left, foundNode);
    }
    else
    {
        findNode(item, root->right, foundNode);
    }
}

給定一個有效節點,您需要同時計算其左子節點和右子節點(二叉樹):

int BSTree::descendants(const Node *root) const
{
    if (!root)
    {
        return 0;
    }
    return 1 + descendants(root->left) + descendants(root->right);
}

無需測試給定的節點是否為葉,只需測試您傳遞的指針是否為NULL (就這一點而言,如果編寫C ++,為什么要為NULL ?如果可以使用C ++ 11或更高版本,則首選nullptr )。 這將自動處理葉子的情況,因為descendants(root->left)descendants(root->right)都將返回0。

注意:該函數實際上將最后返回后代數+ 1

暫無
暫無

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

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