Diameter of Binary Tree
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. This path may or may not pass through the root.
Open official problem prompt ↗Find the number of edges on the longest chain connecting any two nodes in the tree.
Like finding the two most distant leaves on a real tree: at every branch point you measure how far the longest twig reaches on each side and see if joining them beats the current record.
- Input
- root = [1, 2, 3, 4, 5]
- Output
- 3
- Why
- The longest path is 4 -> 2 -> 1 -> 3 (or 5 -> 2 -> 1 -> 3), which uses 3 edges.
The number of nodes is in the range [1, 10^4]-100 <= Node.val <= 100