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?- A. [9, 15, 7, 20, 3] [4, 5, 2, 3, 1]
- B. [9, 7, 15, 20, 3] [4, 5, 2, 3, 1]
- C. [9, 15, 7, 20, 3] [4, 2, 5, 3, 1]
- 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
- Problem: Check whether a tree is height-balanced (every node's subtree heights differ by at most 1). Trees are built by build(xs): a…
- Problem: Return the zigzag level order (left→right, then right→left, alternating). Trees are built by build(xs): a level-order list where…
- Problem: Convert a sorted array into a height-balanced BST and print its preorder. python def pre(a, lo, hi, out): if lo > hi: return out…
- Problem: A tree has n = 10⁵ nodes and arrives as a parent array. You must answer 10⁵ queries 'is u an ancestor of v?'. Which preprocessing…
- Problem: A tree of n nodes is stored as a skewed BST (keys inserted in increasing order). What is the cost of the recursive height…
- Problem: Check whether two trees are mirror images of each other (here: whether a tree is symmetric). Trees are built by build(xs): a…