Given the root of a binary tree, return 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 is represented by the number of edges between nodes.
Input: root = [1,2,3,4,5]
Output: 3
Tree:
1
/ \
2 3
/ \
4 5
Longest path: [4,2,1,3] with 3 edges
Input: root = [1,2]
Output: 1
Tree:
1
/
2
Longest path: [2,1] with 1 edge
The diameter at any node = left_height + right_height (edges on both sides).
Key insight: The longest path through a node is the sum of:
We need to check this for every node, not just the root!
This is a Tree DFS + Global Variable problem with:
Why this works:
Time: O(n) where n = number of nodes
Space: O(h) where h = height
1class TreeNode {
2 int val;
3 TreeNode left;
4 TreeNode right;
5 TreeNode() {}
6 TreeNode(int val) { this.val = val; }
7 TreeNode(int val, TreeNode left, TreeNode right) {
8 this.val = val;
9 this.left = left;
10 this.right = right;
11 }
12}
13
14class Solution {
15 private int diameter = 0;
16
17 public int diameterOfBinaryTree(TreeNode root) {
18 height(root);
19 return diameter;
20 }
21
22 private int height(TreeNode node) {
23 // Base case: null node has height 0
24 if (node == null) {
25 return 0;
26 }
27
28 // Calculate height of left and right subtrees
29 int leftHeight = height(node.left);
30 int rightHeight = height(node.right);
31
32 // Update global diameter (path through this node)
33 diameter = Math.max(diameter, leftHeight + rightHeight);
34
35 // Return height of this subtree
36 return 1 + Math.max(leftHeight, rightHeight);
37 }
38}
39