Skip to content
Onsite

Diameter of Binary Tree

EasyP1Coding

Given the root of a binary tree, return the length of its diameter: the number of edges on the longest path between any two nodes. The path may or may not pass through the root.

Tree nodes have val, left and right. The class TreeNode is already defined for you. The tree arrives in level-order form (as in the examples) and you receive its root, which is null for an empty tree.

Example 1

Input
root = [1,2,3,4,5]
Output
3
Why
The path 4 -> 2 -> 1 -> 3 has 3 edges.

Example 2

Input
root = [1,2]
Output
1

Example 3

Input
root = [1]
Output
0

Constraints

  • The number of nodes is in the range [1, 10^4].
  • -100 <= Node.val <= 100

Hints

Run checks the 3 visible tests, Submit all 9.