Diameter of Binary Tree
Given the root
The diameter 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 is measured in number of edges.
Example 1
Output: 3
Explanation: The path is 4 → 2 → 1 → 3, which has 3 edges.
Example 2
Output: 1
Constraints:
1 <= Number of nodes <= 104-100 <= Node.val <= 100
Contents
Approach 1: Brute Force O(n²)
For each node, compute the height of its left and right subtrees separately.
The diameter through that node is leftHeight + rightHeight
int maxDiameter = 0;
public int diameterOfBinaryTree(TreeNode root) {
computeDiameter(root);
return maxDiameter;
}
private void computeDiameter(TreeNode node) {
if (node == null) return;
int leftH = height(node.left);
int rightH = height(node.right);
maxDiameter = Math.max(maxDiameter, leftH + rightH);
computeDiameter(node.left);
computeDiameter(node.right);
}
private int height(TreeNode node) { // O(n) per call
if (node == null) return 0;
return 1 + Math.max(height(node.left), height(node.right));
}
Note: This is O(n²) because height()
Approach 2: Single DFS: O(n)
Combine height calculation and diameter tracking in a single DFS. At each node, the recursive call returns the height of the subtree, while we update the global maximum diameter as a side-effect.
int maxDiameter = 0;
public int diameterOfBinaryTree(TreeNode root) {
height(root);
return maxDiameter;
}
private int height(TreeNode node) {
if (node == null) return 0;
int leftHeight = height(node.left);
int rightHeight = height(node.right);
// Diameter through this node = left height + right height
maxDiameter = Math.max(maxDiameter, leftHeight + rightHeight);
// Return height of this subtree
return 1 + Math.max(leftHeight, rightHeight);
}
Complexity Analysis
| Approach | Time | Space |
|---|---|---|
| Brute Force | O(n²) | O(h): call stack |
| Single DFS | O(n) | O(h): call stack |