Skip to content
Problem 543 · LeetCode 543(opens in a new tab)

Diameter of Binary Tree

EasyDepth-first search

You get the root of a binary tree. A path joins two nodes by walking along edges, never visiting a node twice. Its length is the number of edges it uses.

Return the length of the longest path in the tree. The path does not have to go through the root.

Example 1

Input:  root = [5, 3, 9, 1, 4, null, null, null, null, 7]
Output: 4
Why:    7 → 4 → 3 → 5 → 9 uses 4 edges
2 more examples and the constraints

Example 2

Input:  root = [8, 6]
Output: 1
Why:    one edge, from 8 to 6

Example 3

Input:  root = [1, 2, null, 3, 4, 5, null, null, 6]
Output: 4
Why:    5 → 3 → 2 → 4 → 6 never touches the root

Constraints

  • 1 ≤ number of nodes ≤ 10,000
  • −100 ≤ Node.val ≤ 100

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Height at every nodeO(n²)
  2. One DFSO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 10,000-node chainVerdict
Height at every nodeO(n²)
Correct; redoes the heights
One DFSO(n)
Best; one visit per node

n = number of nodes, h = height of the tree.

Edge cases to test

  • One node. No edges at all, so the answer is 0.
  • Path avoids the root. In Example 3 the best bend is at node 2, not at the root.
  • A chain. Every node has one child; the answer is n − 1 and the recursion is n deep.
  • Negative values. Values never matter; only the shape does.

Common mistakes

  • Returning left + right from depth instead of 1 + max(left, right), which mixes the path with the depth.
  • Only checking the path through the root and missing a deeper bend.
  • Counting nodes instead of edges, so the answer comes out one too big.

How to talk through it

  1. 1Clarify. Length in edges or nodes? Can the path skip the root? Can the tree be a single node?
  2. 2Find the shape of the answer. Every path has a highest node; there it is left height + right height.
  3. 3Give the simple version. Compute both heights at every node; say why that is O(n²) on a chain.
  4. 4Merge the two jobs. One post-order DFS returns the depth and updates best on the way back up.
  5. 5Test out loud. Run the single node and the path that skips the root before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?