GATE / CS ARCHIVE

GATE CSE 2004 / QUESTION 43

Recursive binary-tree height

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

GATE 2004, Q43 2 marks · MCQ
Report issue

Tree Properties & Traversals

Question 43, GATE 2004: Consider a binary-tree node with fields leftChild, element and rightChild, and this function (max returns the larger argument):
int DoSomething(struct CellNode *ptr) {
  int value=0;
  if(ptr!=NULL) {
    if(ptr->leftChild!=NULL)
      value=1+DoSomething(ptr->leftChild);
    if(ptr->rightChild!=NULL)
      value=max(value,1+DoSomething(ptr->rightChild));
  }
  return value;
}
What is returned when ptr is the root of a nonempty tree?
Options:
(A) Number of leaf nodes
(B) Number of nodes
(C) Number of internal nodes
(D) Height of tree
Question 43, GATE 2004: Consider a binary-tree node with fields leftChild, element and rightChild, and this function (max returns the larger argument):
int DoSomething(struct CellNode *ptr) {
  int value=0;
  if(ptr!=NULL) {
    if(ptr->leftChild!=NULL)
      value=1+DoSomething(ptr->leftChild);
    if(ptr->rightChild!=NULL)
      value=max(value,1+DoSomething(ptr->rightChild));
  }
  return value;
}
What is returned when ptr is the root of a nonempty tree?
Options:
(A) Number of leaf nodes
(B) Number of nodes
(C) Number of internal nodes
(D) Height of tree
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. A leaf returns zero. A node with a child takes one plus that child’s recursively computed value; with two children it takes the maximum.

2. Induction gives the maximum number of edges from the node to a descendant leaf, i.e. height measured in edges. The null check returns zero but no missing child adds an edge.

3. The code does not count nodes or leaves.

4. Teaching check: A singleton tree returns zero, immediately excluding both total-node and leaf counts. A two-edge chain returns two. The recursive maximum chooses the deepest child path, while adding one accounts for the edge from the current node to that child.

Original paper, page 6