GATE / CS ARCHIVE

GATE CSE 2007 / QUESTION 46

Recursive leaf counting in a binary tree

Data Structures · Tree Properties & Traversals · Full GATE CSE 2007 paper

GATE 2007, Q46 2 marks · MCQ
Report issue

Tree Properties & Traversals

Question 46, GATE 2007: CellNode represents a binary-tree node. What does GetValue return when called on the root?
struct CellNode {
    struct CellNode *leftChild;
    int element;
    struct CellNode *rightChild;
};
int GetValue(struct CellNode *ptr) {
    int value=0;
    if(ptr!=NULL) {
        if(ptr->leftChild==NULL && ptr->rightChild==NULL)
            value=1;
        else value=value+GetValue(ptr->leftChild)+GetValue(ptr->rightChild);
    }
    return value;
}
Options:
(A) Number of nodes
(B) Number of internal nodes
(C) Number of leaves
(D) Tree height
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. Approach. Check the two base cases: null contributes zero, and a node with no children contributes one. All other nodes merely add child results, so their own elements and depths are irrelevant.

2. Derivation and interpretation. GetValue returns zero for a null pointer, one when both children are null, and otherwise the sum of the values for the left and right subtrees. By induction on the tree, this counts precisely the leaves: an internal node adds no contribution of its own. Therefore C, the number of leaf nodes, is correct, including zero for an empty tree.

Original paper, page 11