Skip to content
Official PYQ · 2012

GATE CS 2012 Q47 — Trees

Explain with AI

The height of a tree is defined as the number of edges on the longest path in the tree. The function shown in the pseudo-code below is invoked as height (root) to compute the height of a binary tree rooted at the tree pointer root.

int height(treeptr n)
{ if(n == NULL) return -1;
  if(n -> left == NULL)
     if(n -> right == NULL) return 0;
     else return B1; // Box 1
  
  else{h1 = height(n -> left);
       if(n -> right == NULL) return (1+h1);
       else{h2 = height(n -> right);
            return B2; // Box 2
            }
       }
}

The appropriate expressions for the two boxes B1 and B2 are:

Choose one option
View worked solution

Answer: A

The height of a binary tree is defined as the number of edges on the longest path from the root to a leaf. By this definition:

  • An empty tree (NULL) has a height of −1-1.
  • A single-node tree (leaf) has a height of 00.
  • For any node nn, its height is 1+max⁡(height(n→left),height(n→right))1 + \max(\text{height}(n \to \text{left}), \text{height}(n \to \text{right})).

Let us analyze the cases in the given pseudo-code:

1. Determining Box 1 (B1)

This block is executed when n -> left == NULL but n -> right != NULL:

if(n -> left == NULL)
   if(n -> right == NULL) return 0;
   else return B1; // Box 1

Since the left child is empty and the right child exists, the height of the tree rooted at nn is 11 plus the height of its right subtree. Therefore:

B1=1+height(n→right)\text{B1} = 1 + \text{height}(n \to \text{right})

2. Determining Box 2 (B2)

This block is executed when both n -> left and n -> right are not NULL:

else{
     h1 = height(n -> left);
     if(n -> right == NULL) return (1+h1);
     else{
          h2 = height(n -> right);
          return B2; // Box 2
     }
}

Here, h1h1 is the height of the left subtree and h2h2 is the height of the right subtree. Since both subtrees exist, the height of the tree at nn is 11 plus the maximum of the heights of the two subtrees. Therefore:

B2=1+max⁡(h1,h2)\text{B2} = 1 + \max(h1, h2)

Thus, the correct expressions are:

  • B1: (1+height(n→right))(1 + \text{height}(n \to \text{right}))
  • B2: (1+max⁡(h1,h2))(1 + \max(h1, h2))

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

Published
Report a correction
Keep exploringMore Trees questions