progress

~/problems / Trees / Binary trees

Diameter of Binary Tree

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

TreeNode(val, left=None, right=None) is in the starter. Keep it.

Implement diameter_of_binary_tree(root) -> int: the number of edges on the longest path between any two nodes. The path doesn't have to pass through the root. An empty tree or a single node has diameter 0.

#        1
#       / \
#      2   3
#     / \
#    4   5
diameter_of_binary_tree(root)   # 3   (4 -> 2 -> 1 -> 3, or 5 -> 2 -> 1 -> 3)

Up to 100,000 nodes, a few thousand levels deep at most (the Python tests raise the recursion limit for you).

⭐ Bonus: a speed test on a lopsided 34,767-node tree earns a star if you compute each height once (O(n)).

Show hint

The longest path that bends at a node depends on the heights of its two subtrees. One traversal can return each height to its parent while tracking the best bend so far.

Topic: Binary trees. Recursive return values (height, best path), BFS by level, BST invariants.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc