Skip to content
Official PYQ · 2007

GATE CS 2007 Q46 — Trees

Explain with AI

Consider the following C program segment where CellNode\text{CellNode} represents a node in a binary tree:

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);
}

The value returned by GetValue\text{GetValue} when a pointer to the root of a binary tree is passed as its argument is:

Choose one option
View worked solution

Answer: C

To understand what the function GetValue (written as Getvalue in the definition) returns, let us analyze its recursive behavior on a binary tree node pointed to by ptr:

  1. Base Case 1 (Empty Tree): If ptr == NULL, the outer if condition fails, and the function returns value = 0.
  2. Base Case 2 (Leaf Node): If both ptr->leftChild == NULL and ptr->rightChild == NULL, the node is a leaf node. In this case, the condition is met, and value is set to 1.
  3. Recursive Step (Internal Node): If the node is an internal node (i.e., it has at least one child), the else block is executed: value=GetValue(ptr→leftChild)+GetValue(ptr→rightChild)\text{value} = \text{GetValue}(\text{ptr}\rightarrow\text{leftChild}) + \text{GetValue}(\text{ptr}\rightarrow\text{rightChild}) This recursively sums up the values returned by the left and right subtrees.

Since the function returns 1 for every leaf node and 0 for empty subtrees, the total sum returned at the root is the total number of leaf nodes in the binary tree.

Therefore, the correct option is C.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Trees questions