CodingNodes / Trees / Diameter of Binary Tree System design Space play · ←→ step · R restart

Problem

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 or may not pass through the root.

The tree is given in level order, with null for a missing child.

Constraints

  • 1 ≤ number of nodes ≤ 10000
  • -100 ≤ Node.val ≤ 100

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(h)

Time: Every node is visited once, and each visit does constant work.

Space: The recursion goes as deep as the tree is tall, h. That is log n for a balanced tree and n for a chain.

The longest path has a highest node, where it bends. Through that node the path length is the left height plus the right height. So compute heights bottom-up, and at each node try left + right as a candidate for the answer. Keep the largest candidate seen.