Data Structures & AlgorithmsHardProduct company OA

Problem: Rebuild a BST from its preorder in O(n) using an upper bound per recursive call, then print its postorder and height (nodes on the longest path).

Problem: Rebuild a BST from its preorder in O(n) using an upper bound per recursive call, then print its postorder and height (nodes on the longest path).
class T:
    def __init__(s, v): s.v, s.l, s.r = v, None, None
def from_pre(p):
    i = 0
    def go(hi):
        nonlocal i
        if i == len(p) or p[i] > hi: return None
        node = T(p[i]); i += 1
        node.l = go(node.v); node.r = go(hi)
        return node
    return go(float("inf"))
def post(t): return post(t.l) + post(t.r) + [t.v] if t else []
def height(t): return 1 + max(height(t.l), height(t.r)) if t else 0
r = from_pre([9, 4, 2, 6, 5, 13, 11, 15])
print(post(r), height(r))
What is printed?
  1. A. [5, 2, 6, 4, 11, 15, 13, 9] 4
  2. B. [2, 5, 6, 4, 11, 15, 13, 9] 3
  3. C. [2, 4, 5, 6, 9, 11, 13, 15] 4
  4. D. [2, 5, 6, 4, 11, 15, 13, 9] 4

Correct answer: D. [2, 5, 6, 4, 11, 15, 13, 9] 4

Each value is consumed once: a subtree accepts keys below its bound, the left child gets bound = node value, the right child inherits the parent bound. Tree: 9 → (4, 13); 4 → (2, 6); 6 → (5, –); 13 → (11, 15). Postorder 2, 5, 6, 4, 11, 15, 13, 9; longest path 9-4-6-5 has 4 nodes. Inserting keys one by one would also work but costs O(n²) on skewed input.

More Coding Interview Problems questions

Exams that ask this topic