Data Structures & AlgorithmsEasyWipro · Accenture pattern

What is printed? (level-order traversal of the BST built from these keys)

What is printed? (level-order traversal of the BST built from these keys)
def insert(t, k):
    if t is None: return [k, None, None]
    i = 1 if k < t[0] else 2
    t[i] = insert(t[i], k); return t
def pre(t): return [] if t is None else [t[0]] + pre(t[1]) + pre(t[2])
def ino(t): return [] if t is None else ino(t[1]) + [t[0]] + ino(t[2])
def post(t): return [] if t is None else post(t[1]) + post(t[2]) + [t[0]]
from collections import deque
r = None
for k in [50, 30, 70, 20, 40, 60, 80, 10]: r = insert(r, k)
q, out = deque([r]), []
while q:
    t = q.popleft(); out.append(t[0])
    for c in (t[1], t[2]):
        if c: q.append(c)
print(out)
  1. A. [10, 20, 30, 40, 50, 60, 70, 80]
  2. B. [50, 30, 70, 20, 40, 60, 80, 10]
  3. C. [50, 30, 20, 10, 40, 70, 60, 80]
  4. D. [50, 70, 30, 80, 60, 40, 20, 10]

Correct answer: B. [50, 30, 70, 20, 40, 60, 80, 10]

Here the insertion order happens to fill the tree level by level, so the level order equals the insertion order. Inorder would be sorted; preorder is 50, 30, 20, 10, 40, 70, 60, 80. BFS with a queue is O(n).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic