Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Return the diameter of a binary tree (number of EDGES on the longest path between any two nodes).

Problem: Return the diameter of a binary tree (number of EDGES on the longest path between any two nodes).
class T:
    def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs):
    nodes = [T(x) if x is not None else None for x in xs]
    kids = iter(nodes[1:])
    for nd in nodes:
        if nd:
            nd.l = next(kids, None); nd.r = next(kids, None)
    return nodes[0]
best = 0
def height(nd):
    global best
    if not nd: return 0
    l, r = height(nd.l), height(nd.r)
    best = max(best, l + r)
    return 1 + max(l, r)
height(build([1, 2, 3, 4, 5, None, None, 6, None, None, 7, 8]))
print(best)
What is printed?
  1. A. 4
  2. B. 6
  3. C. 7
  4. D. 5

Correct answer: D. 5

Tree: 1 → (2, 3), 2 → (4, 5), 4 → 6 → 8 and 5 → 7. The path 8–6–4–2–5–7 has 5 edges; the path from 8 up to the root and down to 3 also has 5. Counting nodes instead of edges would give 6.

More Coding Interview Problems questions

Exams that ask this topic