Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Rebuild a BST from its preorder traversal (using value bounds) and print its postorder.

Problem: Rebuild a BST from its preorder traversal (using value bounds) and print its postorder.
def post_from_pre(pre):
    i, out = 0, []
    def build(lo, hi):
        nonlocal i
        if i == len(pre) or not (lo < pre[i] < hi): return
        v = pre[i]; i += 1
        build(lo, v); build(v, hi); out.append(v)
    build(float('-inf'), float('inf'))
    return out
print(post_from_pre([8, 5, 1, 7, 10, 12]))
What is printed?
  1. A. [1, 5, 7, 8, 10, 12]
  2. B. [1, 7, 5, 12, 10, 8]
  3. C. [1, 7, 5, 10, 12, 8]
  4. D. [12, 10, 7, 1, 5, 8]

Correct answer: B. [1, 7, 5, 12, 10, 8]

8 is the root; 5, 1, 7 (< 8) form the left subtree with 5 as its root; 10, 12 form the right subtree. Postorder lists children before parents: 1, 7, 5, 12, 10, 8. A preorder alone fixes a BST because the inorder is just the sorted order.

More Coding Interview Problems questions

Exams that ask this topic