Skip to content
Ayotl

← All challenges

Intermediate · easy · binary-tree, dfs, recursion

Diameter of Binary Tree

The challenge

Given the root of a binary tree, return its diameter: the number of edges on the longest path between any two nodes. The path does not have to pass through the root.

Example

      1
     / \
    2   3        ->  3    (4-2-1-3)
   / \
  4   5

        1
       /
      2
     / \         ->  4    (5-3-2-4-6, it skips the root)
    3   4
   /     \
  5       6

Idea: the longest path bends at some node: it goes down into the left subtree on one side and into the right subtree on the other, so at that node its length is height(left) + height(right). One depth-first pass computes every height and, on the way, keeps the largest of those sums. Each node is visited once: time O(n), and O(h) of stack for a tree of height h.

The solution

# Diameter of Binary Tree - ayotl.dev
class T:
    def __init__(self, v, l=None, r=None):
        self.v, self.l, self.r = v, l, r


def diameter(root):
    best = 0

    def height(t):
        nonlocal best
        if not t:
            return 0
        l, r = height(t.l), height(t.r)
        # the longest path bending here
        best = max(best, l + r)
        return 1 + max(l, r)

    height(root)
    return best


a = T(1, T(2, T(4), T(5)), T(3))
b = T(1, T(2, T(3, T(5)),
             T(4, None, T(6))))
print(diameter(a))
print(diameter(b))

$ python3 diameter_of_binary_tree.py

3

4

The video

Watch on YouTube →