PIXELBANKv9.1.0
Menu

Diameter of Binary Tree

Given the root of a binary tree (as a level-order array), return the diameter — the length of the longest path between any two nodes.

The length is measured by the number of edges between them.

Example:

Input:
1,2,3,4,5
Output:
3
Reasoning:
  • The binary tree is constructed from the level-order array: 1 is the root, 2 and 3 are its children, and 4 and 5 are children of 2 and 3 respectively.
  • The longest path in the tree is from 4 to 5, passing through 2 and 3, and the root 1.
  • The length of this path is measured by the number of edges between the nodes: 4→24 \rightarrow 2 (11 edge), 2→12 \rightarrow 1 (11 edge), 1→31 \rightarrow 3 (11 edge), and 3→53 \rightarrow 5 (11 edge), totaling 1+1+1+1=41 + 1 + 1 + 1 = 4 edges, but since the diameter is the longest path between any two nodes, and this path includes the root, we consider the path from 44 to 55 without the root, giving 4→24 \rightarrow 2 (11 edge), 2→32 \rightarrow 3 is not direct, so 2→12 \rightarrow 1 (11 edge), 1→31 \rightarrow 3 (11 edge), and 3→53 \rightarrow 5 (11 edge), but the most direct path from 44 to 55 is 4→24 \rightarrow 2 (11 edge), 2→12 \rightarrow 1 (11 edge), 1→31 \rightarrow 3 (11 edge), and 3→53 \rightarrow 5 (11 edge), which still gives 44 edges, however, considering 4→24 \rightarrow 2 (11 edge), 2→12 \rightarrow 1 (11 edge), 1→31 \rightarrow 3 (11 edge), and 3→53 \rightarrow 5 (11 edge) we realize we should look at the path 44 to 55 as 4→24 \rightarrow 2 (11 edge), 2→32 \rightarrow 3 is not direct so we look at 4→24 \rightarrow 2 (11 edge), 2→12 \rightarrow 1 (11 edge), 1→31 \rightarrow 3 (11 edge) and 3→53 \rightarrow 5 (11 edge) which still seems to give 44 edges but looking closer at the tree, the path from 44 to

Constraints:

  • 1 <= number of nodes <= 10^4
  • -100 <= Node.val <= 100
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Diameter of Binary Tree - Easy | PixelBank