Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Convert a sorted array into a height-balanced BST and print its preorder.

Problem: Convert a sorted array into a height-balanced BST and print its preorder.
def pre(a, lo, hi, out):
    if lo > hi: return out
    mid = (lo + hi) // 2
    out.append(a[mid])
    pre(a, lo, mid - 1, out)
    pre(a, mid + 1, hi, out)
    return out
print(pre([1, 2, 3, 4, 5, 6, 7], 0, 6, []), pre([1, 2, 3, 4], 0, 3, []))
What is printed?
  1. A. [4, 2, 1, 3, 6, 5, 7] [3, 2, 1, 4]
  2. B. [4, 2, 6, 1, 3, 5, 7] [2, 1, 3, 4]
  3. C. [4, 2, 1, 3, 6, 5, 7] [2, 1, 3, 4]
  4. D. [1, 2, 3, 4, 5, 6, 7] [2, 1, 3, 4]

Correct answer: C. [4, 2, 1, 3, 6, 5, 7] [2, 1, 3, 4]

Pick the middle as the root, recurse on both halves. With an even length, (lo + hi) // 2 picks the lower middle (2), so 3 and 4 form the right subtree. [4, 2, 6, 1, 3, 5, 7] is the level order, not the preorder. O(n).

More Coding Interview Problems questions

Exams that ask this topic