Start learning free

LESSON 479 OF 673 · BINARY TREES

Binary Tree Diameter

Practice O(n)

You get the root of a binary tree. Return its diameter.

The diameter is the number of edges on the longest path between two nodes. The path can start and end at any node. It doesn't have to pass through the root. A tree with one node has a diameter of 0.

The trees below are listed level by level, top to bottom and left to right. A missing child is written as None.

 

Example 1:

4 2 1 6 3 5
Input: root = [4,2,None,1,6,3,None,None,5]
Output: 4
Explanation: The blue path 3 → 1 → 2 → 6 → 5 is the longest.
It has 4 edges.
It doesn't use the root 4.
A path through 4 has at most 3 edges.

Example 2:

Input: root = [3,1,2,None,None,None,4]
Output: 3
Explanation: The longest path is 1 → 3 → 2 → 4.
It goes through the root and has 3 edges.

Example 3:

Input: root = [1]
Output: 0
Explanation: The tree has one node and no edges.

 

Constraints:

  • 1 to 1,000 nodes.
  • With n nodes, the values are 1 to n, each used once.
  • The values don't change the answer.
STEP 1 OF 10
    Ctrl + Enter to check