📜  门| GATE-CS-2014-(Set-3) |第 65 题

📅  最后修改于: 2021-09-26 03:45:24             🧑  作者: Mango

考虑下面给出的伪代码。函数DoSomething() 将指向由 leftMostChild-rightSibling 表示形式表示的任意树的根的指针作为参数。
树的每个节点都是 treeNode 类型。

typedef struct treeNode* treeptr;
struct treeNode
{
    treeptr leftMostChild, rightSibling;
};
int DoSomething (treeptr tree)
{
    int value=0;
    if (tree != NULL)
    {
        if (tree->leftMostChild == NULL)
            value = 1;
        else
            value = DoSomething(tree->leftMostChild);
        value = value + DoSomething(tree->rightSibling);
    }
    return(value);
}

当指针树的根作为参数DoSomething的传递,则返回值由函数对应于
(A)树中内部节点的数量。

(B)树的高度。
(C)树中没有右兄弟节点的节点数。

(D)树中叶节点的数量。答案: (D)
说明:该函数计算使用 leftMostChild-rightSibling 表示法表示的树的叶节点数。

下面是与添加到演示函数是如何工作的评论函数。

int DoSomething (treeptr tree)
{
    // If tree is empty, 0 is returned
    int value = 0;
  
    // IF tree is not empty
    if (tree != NULL)
    {
        // IF this is a leaf node, then values is initialized as 1
        if (tree->leftMostChild == NULL)
            value = 1;
  
        // Else value is initialized as the value returned by leftmost
        // child which in turn calls for the other children of this node
        // Using last call "value = value + DoSomething(tree->rightSibling);"
        else
            value = DoSomething(tree->leftMostChild);
  
        // Add value returned by right sibling
        value = value + DoSomething(tree->rightSibling);
    }
    return(value);
}

这个问题的测验