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
1,2,3,4,5
3
- Input: the level-order array
1,2,3,4,5fills the tree row by row, left to right:1is the root,2and3are its left and right children, and4and5are both children of2. - Paths between leaves: has edges. has edges.
- Why is the maximum: node
3sits edge below the root, while4and5sit edges below it. A path joining the two sides of the root therefore has edges. - Output:
3, a count of edges, not nodes: the path visits nodes but uses edges. - Notice: the longest path need not touch the root. Drop
3and hang a child under4and a child under5: then has edges, while any path touching the root has at most . A single-node tree has diameter .
Constraints
- 1 <= number of nodes <= 10^4
- -100 <= Node.val <= 100