Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Return the diameter of a tree – the number of edges on the longest path between any two nodes. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
Problem: Return the diameter of a tree – the number of edges on the longest path between any two nodes. 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 diameter(root):
best = 0
def depth(t):
nonlocal best
if not t: return 0
a, b = depth(t.l), depth(t.r)
best = max(best, a + b)
return 1 + max(a, b)
depth(root)
return best
print(diameter(build([1, 2, None, 3, 4, None, None, 5, None, 6, None, None, None, None, None, 7, None, None, None, 8])))What is printed?- A. 4
- B. 6
- C. 3
- D. 7
Correct answer: B. 6
The longest path need not pass through the root: node 2 has chains 3 → 5 → 7 and 4 → 6 → 8 of depth 3 each, so the path 7…8 has 3 + 3 = 6 edges. Counting nodes instead of edges gives 7, forcing the path through the root gives 4, and reporting the depth of one chain instead of adding both gives 3.
More Coding Interview Problems questions
- Problem: Find the maximum sum of any path in a tree (a path goes between any two nodes, need not pass through the root, values may be…
- Problem: Count root-to-leaf paths whose values sum to a target. Trees are built by build(xs): a level-order list where index i has…
- Problem: Count downward paths (starting anywhere, ending anywhere below) that sum to k, using prefix sums on the root-to-node path. Trees…
- Problem: Serialize a tree in preorder with '#' for missing children, then count the nodes from the string alone. python class T: def…
- Problem: Rebuild a tree from its preorder and inorder sequences (distinct values) and print its postorder. python def post(pre, ino): if…
- 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…