82. Diameter of Binary Tree
Find the longest path connecting any two nodes of the tree. That path can pass through the root, but it does not have to.
A path cannot branch or revisit a node. Unlike maximum depth, this problem counts edges rather than nodes.
Example 1
Input
[1,2,3,4,5]
Output
3
Explanation: A longest path is 4–2–1–3, with three edges.
Example 2
Input
[0,1,null,2,3,4,null,null,5]
Output
4
Explanation: The longest path 4–2–1–3–5 crosses node 1, not root 0.
Constraints
0 <= node count per tree <= 105-231 <= node.value <= 231 - 1- Each input is a proper binary tree: no cycles or shared child nodes. Null trees are permitted.
Hints
Hint 1
Choose the highest node of a candidate path.
Hint 2
You need one best downward arm from each child.
Hint 3
Postorder computes heights once; update a global sum of the two arms at every node.
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
Child heights produce an edge count
[1,2,3,4,5]
3