ProgrammingHardProduct company OA · GATE CS

A binary tree is stored with child indices (−1 for none). What does h(0) return?

A binary tree is stored with child indices (−1 for none). What does h(0) return?
int L[] = {1, 3, -1, -1, -1}, R[] = {2, 4, -1, -1, -1};
int h(int n) {
    if (n < 0) return 0;
    int a = h(L[n]), b = h(R[n]);
    return 1 + (a > b ? a : b);
}
  1. A. 5
  2. B. 2
  3. C. 4
  4. D. 3

Correct answer: D. 3

Node 0 has children 1 and 2; node 1 has children 3 and 4. The longest root-to-leaf path is 0 → 1 → 3, which has 3 nodes, so the height (counting nodes) is 3. '5' is the number of nodes; '2' counts edges.

More C Programming questions

Exams that ask this topic