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

📅  最后修改于: 2021-06-28 22:07:13             🧑  作者: 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)树中的内部节点数。

(二)树的高度。
(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);
}

这个问题的测验