AceYourInterviews
Checking sign-in…

82. Diameter of Binary Tree

CorePostorder child heights plus a global two-arm edge count

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.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Child heights produce an edge count

[1,2,3,4,5]
3