Skip to content
Official PYQ · 2014

GATE CS 2014 Set 3 Q41 — Trees

Explain with AI

Consider the pseudocode given below. The function DoSomething()DoSomething() takes as argument a pointer to the root of an arbitrary tree represented by the leftMostChild−rightSiblingleftMostChild-rightSibling representation. Each node of the tree is of type treeNodetreeNode.

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

When the pointer to the root of a tree is passed as the argument to DoSomethingDoSomething, the value returned by the function corresponds to the 

Choose one option
View worked solution

Answer: D

To understand what the function DoSomething(tree) computes, let us analyze how the Left-Child Right-Sibling (LCRS) representation works:

  • leftMostChild points to the first child of the node. If this is NULL, the node has no children in the original tree.
  • rightSibling points to the immediate sibling of the node.

Let us trace the recursive function DoSomething(tree):

  1. Base Case 1: If tree == NULL, the function returns 0.
  2. Base Case 2: If tree->leftMostChild == NULL, the node has no children in the original tree. This means the node is a leaf node. Thus, value is set to 1.
  3. Recursive Step 1 (Children): If tree->leftMostChild != NULL, the node is an internal node. The function recursively counts the leaves in the subtree of its children by calling DoSomething(tree->leftMostChild).
  4. Recursive Step 2 (Siblings): Finally, the function adds the count of leaves from the sibling subtrees by adding DoSomething(tree->rightSibling).

By combining the leaf counts of the children and the siblings, the function recursively traverses the entire tree and returns the total number of leaf nodes in the tree.

Therefore, the correct option is D.

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

Published
Report a correction
Keep exploringMore Trees questions