GATE Computer ScienceHardGATE CS (PYQ pattern)

A complete binary tree with 20 nodes is stored in A[1..20] with A[i] = i, the children of i at 2i and 2i + 1. The routine v(i) does: if i > 20 return; v(2i); print A[i]; v(2i + 1). In the output of v(1), at which positions (1-indexed) are 1 and 5 printed?

  1. A. 13 and 11
  2. B. 12 and 11
  3. C. 13 and 12
  4. D. 11 and 10

Correct answer: A. 13 and 11

Inorder prints the whole left subtree of the root first. The left subtree of 1 contains 2, 4, 5, 8, 9, 10, 11, 16, 17, 18, 19, 20: twelve nodes, so 1 is printed 13th. Inside the subtree of 2, the left part rooted at 4 (4, 8, 9, 16, 17, 18, 19) has 7 nodes, then 2; the subtree of 5 starts with 10 and its child 20, so 5 comes after 7 + 1 + 2 nodes: position 11. Full order: 16 8 17 4 18 9 19 2 20 10 5 11 1 12 6 13 3 14 7 15.

More Programming and Data Structures (GATE) questions

Exams that ask this topic