543. Diameter of Binary Tree
Given the root of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
The length of a path between two nodes is represented by the number of edges between them.
Example 1:
Example 2:
- The number of nodes in the tree is in the range [1, 104].
- -100 <= Node.val <= 100
Constraints:
Notes
Intuition
The diameter passes through some node where the path goes down through its left and right subtrees. At each node, left_height + right_height is a candidate for the diameter. Track the maximum across all nodes.
Implementation
Use DFS that returns the height of each subtree while updating a global result. Base case: null node returns 0. For each node, compute left and right heights recursively. Update the global maximum with left + right (the path through this node). Return 1 + max(left, right) as this subtree's height.
Edge-cases
In Python, use nonlocal to modify variables from an enclosing scope within a nested function. The diameter could be entirely within one subtree.
- Time: O(n) — visit each node once
- Space: O(n) — recursion stack depth in worst case