Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Flatten a tree into a 'linked list' in preorder using right pointers, then print the values along the right pointers. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
Problem: Flatten a tree into a 'linked list' in preorder using right pointers, then print the values along the right pointers. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
class T:
def __init__(self, v, l=None, r=None):
self.v, self.l, self.r = v, l, r
def build(xs, i=0):
if i >= len(xs) or xs[i] is None: return None
return T(xs[i], build(xs, 2*i+1), build(xs, 2*i+2))
def flatten(t):
cur = t
while cur:
if cur.l:
p = cur.l
while p.r: p = p.r
p.r, cur.r, cur.l = cur.r, cur.l, None
cur = cur.r
r = build([1, 2, 5, 3, 4, None, 6])
flatten(r)
out = []
while r: out.append(r.v); r = r.r
print(out)What is printed?- A. [1, 2, 3, 4, 5, 6]
- B. [3, 2, 4, 1, 5, 6]
- C. [1, 2, 5, 3, 4, 6]
- D. [1, 5, 6, 2, 3, 4]
Correct answer: A. [1, 2, 3, 4, 5, 6]
Morris-style: hang the right subtree after the rightmost node of the left subtree, move the left subtree to the right, and continue. The result follows preorder 1, 2, 3, 4, 5, 6 in O(n) time and O(1) extra space. [1, 2, 5, 3, 4, 6] is the level order.
More Coding Interview Problems questions
- Problem: A trie stores n words of average length L over a 26-letter alphabet. Autocomplete must list whether any word starts with a prefix…
- Problem: Insert words into a trie and count how many stored words start with a given prefix. python def make(words): root = {} for w in…
- Problem: Count islands (groups of '1' cells connected up, down, left or right) on a satellite grid. python def islands(g): R, C = len(g)…
- Problem: In a grid of fresh (1) and rotten (2) oranges, every minute rot spreads to 4-neighbours. Return the minutes until no fresh orange…
- Problem: Courses with prerequisites [a, b] (b before a). Return one valid order using Kahn's algorithm with a min-heap for ties, or [] if…
- Problem: Detect a cycle in a directed dependency graph with three-colour DFS. python def hascycle(n, edges): adj = [[] for in range(n)]…