Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Rebuild a binary tree from its inorder and postorder traversals (distinct values) and print its preorder.

Problem: Rebuild a binary tree from its inorder and postorder traversals (distinct values) and print its preorder.
def pre_from(ino, post):
    idx = {v: i for i, v in enumerate(ino)}; out = []
    def go(lo, hi, p_hi):
        if lo > hi: return
        root = post[p_hi]; out.append(root); m = idx[root]
        right = hi - m
        go(lo, m - 1, p_hi - right - 1)
        go(m + 1, hi, p_hi - 1)
    go(0, len(ino) - 1, len(post) - 1)
    return out
print(pre_from([4, 2, 5, 1, 6, 3, 7], [4, 5, 2, 6, 7, 3, 1]))
What is printed?
  1. A. [1, 3, 7, 6, 2, 5, 4]
  2. B. [1, 2, 4, 5, 3, 6, 7]
  3. C. [4, 2, 5, 1, 6, 3, 7]
  4. D. [1, 2, 4, 5, 3, 7, 6]

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

The last postorder value (1) is the root; inorder splits it into left {4, 2, 5} and right {6, 3, 7}. In postorder the right subtree occupies the positions just before the root, so its size (3) locates the left subtree's root (2). The tree is a perfect tree 1 → (2 → 4, 5), (3 → 6, 7).

More Coding Interview Problems questions

Exams that ask this topic