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?
  1. A. 4
  2. B. 6
  3. C. 3
  4. 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

Exams that ask this topic