#543

Diameter of Binary Tree

Easy Height with a global best

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the number of edges on the longest path between any two nodes of a binary tree (the path need not pass through the root).

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the longest path (in edges) between any two nodes.

Why this works: the longest path through a node = left height + right height. Compute heights once and update a global best.

Example: 1 (2 (4, 5), 3)

at 2: heights 1 + 1 = 2at 1: heights 2 + 1 = 3 → path 4-2-1-3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Calling a separate height function at every node — O(n²) on a skewed tree.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(h).
Topic: Binary Trees
🎬 Episodes 53–60: video coming soon