Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Insert keys into an empty BST in the given order and report the preorder traversal.

Problem: Insert keys into an empty BST in the given order and report the preorder traversal.
def insert(t, k):
    if t is None: return [k, None, None]
    if k < t[0]: t[1] = insert(t[1], k)
    else: t[2] = insert(t[2], k)
    return t
def pre(t): return [] if t is None else [t[0]] + pre(t[1]) + pre(t[2])
root = None
for k in [50, 30, 70, 20, 40, 60, 80, 35]:
    root = insert(root, k)
print(pre(root))
What is printed?
  1. A. [50, 30, 70, 20, 40, 60, 80, 35]
  2. B. [20, 30, 35, 40, 50, 60, 70, 80]
  3. C. [50, 30, 20, 35, 40, 70, 60, 80]
  4. D. [50, 30, 20, 40, 35, 70, 60, 80]

Correct answer: D. [50, 30, 20, 40, 35, 70, 60, 80]

35 goes left of 50, right of 30, left of 40. Preorder (root, left, right) then reads 50, 30, 20, 40, 35, 70, 60, 80. The insertion order is the level order only for a perfectly filled tree; the sorted list is the inorder. Each insert is O(h).

More Coding Interview Problems questions

Exams that ask this topic