Description

Given the root of a binary tree, return the length of the diameter of the tree. The diameter is the length of the longest path between any two nodes in a tree.

Examples

Input:root = [1,2,3,4,5]
Output:3
Explanation:

Path 4 -> 2 -> 1 -> 3 or 5 -> 2 -> 1 -> 3.

Input:root = [1]
Output:0
Explanation:

A single node tree has no edges, so the diameter is 0. The longest path is just the node itself with length 0.

Input:root = [3,9,20,null,null,15,7]
Output:3
Explanation:

The longest path is 15 -> 20 -> 3 -> 9 (or 7 -> 20 -> 3 -> 9), which has 3 edges. This demonstrates a diameter path that goes through the root.

Constraints

  • Number of nodes is in range [1, 10⁴]
  • -100 ≤ Node.val ≤ 100

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!