Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

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

Problem: Rebuild a tree from its preorder and inorder sequences (distinct values) and print its postorder.
def post(pre, ino):
    if not pre: return []
    root = pre[0]
    i = ino.index(root)
    return post(pre[1:i + 1], ino[:i]) + post(pre[i + 1:], ino[i + 1:]) + [root]
print(post([3, 9, 20, 15, 7], [9, 3, 15, 20, 7]), post([1, 2, 4, 5, 3], [4, 2, 5, 1, 3]))
What is printed?
  1. A. [9, 15, 7, 20, 3] [4, 5, 2, 3, 1]
  2. B. [9, 7, 15, 20, 3] [4, 5, 2, 3, 1]
  3. C. [9, 15, 7, 20, 3] [4, 2, 5, 3, 1]
  4. D. [15, 7, 9, 20, 3] [5, 4, 2, 3, 1]

Correct answer: A. [9, 15, 7, 20, 3] [4, 5, 2, 3, 1]

The first preorder value is the root; its position in the inorder list splits the left and right subtrees, whose sizes then split the preorder list. This version is O(n²) because of index() and slicing; with a value→index map it is O(n).

More Coding Interview Problems questions

Exams that ask this topic