height(n) returns 1 + max(l, r) and updates best = max(best, l + r).
Approach 1
class Solution {
private int best = 0;
public int diameterOfBinaryTree(TreeNode root) {
height(root);
return best;
}
private int height(TreeNode n) {
if (n == null) return 0;
int l = height(n.left), r = height(n.right);
best = Math.max(best, l + r);
return 1 + Math.max(l, r);
}
}