Example 1
- Input
- root = [1,2,3,4,5]
- Output
- 3
The path 4 → 2 → 1 → 3 has 3 edges. Path 5 → 2 → 1 → 3 ties it. The two child heights at root 1 are 2 and 1, while the candidate at node 2 has only 2 edges.
Given the root of a binary tree, return the number of edges on the longest path between any two nodes. That longest path may or may not pass through the root.
Given the root of a binary tree, return the length of the diameter of the tree.
The diameter is the longest path between any two nodes, measured in edges rather than nodes, and it may or may not pass through the root.
The path 4 → 2 → 1 → 3 has 3 edges. Path 5 → 2 → 1 → 3 ties it. The two child heights at root 1 are 2 and 1, while the candidate at node 2 has only 2 edges.
The only nonempty path joins 1 to 2 with one edge. Root 1 combines child heights 1 and 0; node 2 contributes a candidate of 0.
A single node has no edge to traverse. Both child heights are 0, so the diameter is 0 even though the tree height is 1.
The longest path is 5 → 3 → 2 → 4 → 6, entirely below root 1. At node 2 the child heights are 2 and 2, giving 4 edges; root 1 combines heights 3 and 0, giving only 3.
A path between two nodes has one highest node, where its two downward arms meet. Height counts nodes below a child, with an empty child having height 0: those child heights also count the edges from their parent to the deepest descendants. In Example 1, root 1 joins left height 2 and right height 1 into 3 edges. The winning highest node can be below the root, so compare this sum at every node; return only a single downward height to its parent.
Reveal Top Down Recompute: intuition, complexity, and code
Return child summaries upward while updating a shared best, which turns repeated top-down measuring into one bottom-up pass.