ProgrammingVery hardAmazon 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: 50, 30, 70, 20, 40, 60, 80, 35, 45, 65
Function leaves(Node t)
    if (t == NULL) return 0
    if (t.left == NULL AND t.right == NULL) return 1
    return leaves(t.left) + leaves(t.right)
End Function
Function depth(Node t)              // number of edges on the longest downward path
    if (t == NULL) return -1
    return 1 + max(depth(t.left), depth(t.right))
End Function
Print leaves(root), depth(root.left) + depth(root.right) + 2
  1. A. 5 6
  2. B. 4 6
  3. C. 5 5
  4. D. 6 7

Correct answer: A. 5 6

Leaves: 20, 35, 45, 65, 80 → 5. The left subtree (30) has depth 2 (30–40–35) and the right subtree (70) depth 2 (70–60–65); adding the two edges to the root gives the longest path through the root: 2 + 2 + 2 = 6 edges, e.g. 35–40–30–50–70–60–65. Output 5 6.

More Pseudocode and Code Tracing questions

Exams that ask this topic