Data Structures & AlgorithmsEasyWipro · Accenture pattern

What is printed? (recursion output order)

What is printed? (recursion output order)
out = []
def f(n):
    if n == 0: return
    out.append(n)
    f(n - 1)
    out.append(n)
f(3)
print(*out)
  1. A. 3 2 1 1 2 3
  2. B. 3 2 1
  3. C. 1 2 3 3 2 1
  4. D. 3 2 1 3 2 1

Correct answer: A. 3 2 1 1 2 3

Each call prints n on the way down, recurses, then prints n again on the way back up as the stack unwinds: 3 2 1 then 1 2 3. Depth n, 2n prints, O(n).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic