Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Rebuild a BST from its preorder traversal (using value bounds) and print its postorder.
Problem: Rebuild a BST from its preorder traversal (using value bounds) and print its postorder.
def post_from_pre(pre):
i, out = 0, []
def build(lo, hi):
nonlocal i
if i == len(pre) or not (lo < pre[i] < hi): return
v = pre[i]; i += 1
build(lo, v); build(v, hi); out.append(v)
build(float('-inf'), float('inf'))
return out
print(post_from_pre([8, 5, 1, 7, 10, 12]))What is printed?- A. [1, 5, 7, 8, 10, 12]
- B. [1, 7, 5, 12, 10, 8]
- C. [1, 7, 5, 10, 12, 8]
- D. [12, 10, 7, 1, 5, 8]
Correct answer: B. [1, 7, 5, 12, 10, 8]
8 is the root; 5, 1, 7 (< 8) form the left subtree with 5 as its root; 10, 12 form the right subtree. Postorder lists children before parents: 1, 7, 5, 12, 10, 8. A preorder alone fixes a BST because the inorder is just the sorted order.
More Coding Interview Problems questions
- Problem: For every node of a tree, compute the sum of distances to all other nodes in O(n) with re-rooting: ans[child] = ans[parent] −…
- Problem: Walk along buildings; climbing up by d costs d bricks or one ladder (going down is free). Use ladders on the largest climbs (a…
- Problem: Return the k pairs (u from a, v from b) with the smallest sums, using a heap seeded with (a[i], b[0]). python import heapq def…
- Problem: Median of two sorted arrays in O(log(min(m, n))) by binary searching the partition of the shorter array. python def median(a, b)…
- Problem: Find the k-th positive integer missing from a strictly increasing array, by binary search on 'missing before index i' = a[i] − (i…
- Problem: Find the area of the largest square of 1s in a binary matrix. python def square(m): R, C = len(m), len(m[0]); dp = [[0] (C + 1)…