← Tree Traversal

Micro-Drill #139 — Diameter of binary tree

Tree Traversal Target: 10s

Diameter is the max left_height + right_height at any node. Track global max during DFS.

dia = 0
def h(n):
    global dia
    if not n: return 0
    l, r = h(n.left), h(n.right)
    dia = max(dia, l + r)
    return 1 + max(l, r)

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #138 Micro #140 →