Diameter of Binary Tree

EasyTree recursionLeetCode 543 ↗World 3-5
0:00 / 0:00

Find the longest path between any two nodes. Each node asks its children for their heights, and the path bending through it is left plus right.

▼

The problem

LeetCode 543 (Easy). 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.

Examples (both animated):

TRY IT ON LEETCODE ▶

The solution

def diameterOfBinaryTree(root):
    best = 0
    def height(node):
        nonlocal best
        if not node:
            return 0
        left = height(node.left)
        right = height(node.right)
        best = max(best, left + right)
        return 1 + max(left, right)
    height(root)
    return best

Transcript

Diameter of Binary Tree. Given the root of a binary tree, return its diameter: the number of edges on the longest path between any two nodes. The path may go up and back down, and it doesn't have to pass through the root.

Here's the example: one on top, two and three below it, and four and five under two. The longest path runs from four, up through two and one, then down to three. That's three edges, so the diameter is three.

But look at this tree. Its longest path runs from five to six: four edges, and it bends at two. The root isn't on it at all.

The naive way: at every node, measure its left and right heights from scratch, and add them. Each measurement walks a whole subtree again. On a long, skewed tree, that's n, plus n minus one, and so on: n squared.

The key idea: every path has one highest node, where it bends. There, its length is the left height plus the right height. So work up from the leaves. Each node takes its children's heights, updates the best with their sum, and passes one plus the bigger height up to its parent.

In code, an empty node has height zero. Get the left and right heights. Update best with their sum: the path that bends here. Then return one plus the larger. Call it on the root, and best is the answer.

Let's run it on the second tree, from the leaves up. Five is a leaf: zero plus zero, so it returns one. Three gets one and zero: best becomes one, and three returns two. Six returns one, and four returns two. At two, two plus two is four: best jumps to four, and two returns three. At the root, three plus zero is only three, so best stays four.

Every node is visited once, so the time is O of n. The recursion holds one path of calls at a time, so the space is O of the tree's height.

Heights go up, left plus right at every bend, keep the best. That's Diameter of Binary Tree.