ProgrammingHardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Insert into an empty BST, in this order: 8, 3, 10, 1, 6, 14, 4, 7, 13
Queue q = {root}
while (q not empty)
    Node t = dequeue(q)
    Print t.key
    if (t.left != NULL) enqueue(q, t.left)
    if (t.right != NULL) enqueue(q, t.right)
end while
  1. A. 1 3 4 6 7 8 10 13 14
  2. B. 8 3 10 1 6 14 4 7 13
  3. C. 8 3 1 6 4 7 10 14 13
  4. D. 8 3 10 1 6 4 7 14 13

Correct answer: B. 8 3 10 1 6 14 4 7 13

A queue gives level-order traversal: level 1: 8; level 2: 3, 10; level 3: 1, 6, 14; level 4: 4, 7, 13. Output 8 3 10 1 6 14 4 7 13 — here it equals the insertion order, but only by coincidence.

More Pseudocode and Code Tracing questions

Exams that ask this topic