ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
// BST: smaller keys go left, larger (or equal) keys go right
Insert into an empty BST, in this order: 8, 3, 10, 1, 6, 14, 4, 7, 13
Function height(Node t)
    if (t == NULL)
        return 0
    end if
    return 1 + max(height(t.left), height(t.right))
End Function
Integer comps = number of nodes visited while searching for 7 from the root
Print height(root), comps
  1. A. 3 4
  2. B. 4 3
  3. C. 4 4
  4. D. 5 4

Correct answer: C. 4 4

The longest root-to-leaf paths are 8–3–6–4, 8–3–6–7 and 8–10–14–13, each with 4 nodes, so height = 4. Searching for 7 visits 8, 3, 6, 7: 4 nodes. Output 4 4.

More Pseudocode and Code Tracing questions

Exams that ask this topic