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?- A. [1, 3, 7, 6, 2, 5, 4]
- B. [1, 2, 4, 5, 3, 6, 7]
- C. [4, 2, 5, 1, 6, 3, 7]
- 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
- Problem: Lowest common ancestor in a general binary tree (not a BST), with the recursive 'return whichever side found something' method…
- Problem: Delete the nodes with given values from a binary tree and return the roots of the remaining forest, sorted. python class T: def…
- Problem: Print the boundary of a binary tree anticlockwise: root, left boundary (excluding leaves), all leaves left to right, then the…
- Problem: Convert a BST so each node's value becomes the sum of all values ≥ it (reverse inorder with a running sum); print the new…
- Problem: Count subtrees in which every node has the same value. python class T: def init(s, v): s.v, s.l, s.r = v, None, None def…
- Problem: Rain falls on a 2-D height map. Compute the trapped water volume with a min-heap that grows inward from the border. python import…