SDE & MLE Prep

543. Diameter of Binary Tree

Problem

Return the diameter of a binary tree: the number of edges on the longest path between any two nodes. The path doesn't have to pass through the root.

Example: [1,2,3,4,5] → 3 (path 4 → 2 → 1 → 3)

The longest path through a node = height(left) + height(right). Return height upward, update a global best on the way.

Complexity: O(n).

class Solution:
    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        best = 0

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

        height(root)
        return best