GATE / CS ARCHIVE

GATE CSE 2012 / QUESTION 47

Recursive rooted height and wording mismatch

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

GATE 2012, Q47 2 marks · MCQ
Report issue

Tree Properties & Traversals

Question 47, GATE 2012: The source defines tree height as “the number of edges on the longest path in the tree” and gives this rooted-tree routine. Fill B1,B2:
int height(treeptr n) {
 if(n==NULL) return -1;
 if(n->left==NULL)
   if(n->right==NULL) return 0; else return B1;
 else { h1=height(n->left);
   if(n->right==NULL) return 1+h1;
   else { h2=height(n->right); return B2; }
 }
}
(A) B1=1+height(n->right), B2=1+max(h1,h2).
(B) B1=height(n->right), B2=1+max(h1,h2).
(C) B1=height(n->right), B2=max(h1,h2).
(D) B1=1+height(n->right), B2=max(h1,h2).
Tap to enlarge
Your answer
Answer & solution

Official answer: A

For the conventional rooted height, a leaf has height 0 and every parent-to-child step adds one edge. If only the right child exists, B1 must be 1+height(n→right). If both exist, B2 must be 1+max(h1, h2). Thus A is the intended rooted-height answer and matches the official key. However, the opening sentence literally defines the longest path anywhere in the tree, which is its diameter, not necessarily its root-to-leaf height. A root with two leaf children has rooted height 1 but diameter 2; none of the listed B2 expressions returns 2 for that example. Preserve this wording defect rather than claiming the code computes the literal definition.

Check: Check a node with only a right leaf: the child returns 0 and the parent must return 1, forcing B1’s +1. With two children, choose the larger subtree height and add the edge from the current node, forcing B2’s +1.

Original paper, page 12 · Answer key