繁体   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