StreakPeaked· Practice

ExamsGATETechnical

Consider the pseudocode given below. The function DoSomething() takes an argument a pointer to the root of an arbitrary tree represented by the leftMostChild-rightSibling representation. Each node of the tree is of type 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); } When the pointer to the root of a tree is passed as the argument to DoSomething, the value returned by the function corresponds to the

  1. number of internal nodes in the tree.
  2. height of the tree.
  3. number of nodes without a right sibling in the tree.
  4. number of leaf nodes in the tree.

Correct answer: number of leaf nodes in the tree.

Solution

The function counts leaf nodes by checking if a node has no children (leftMostChild is NULL) and returns 1 for each leaf. It recursively processes the leftmost child and right sibling, ensuring all leaf nodes are counted.

Related GATE Technical questions

⚔️ Practice GATE Technical free + battle 1v1 →