My solution without using a global variable.
class Solution {
private class Int {
int val;
Int(int val) {
this.val = val;
}
}
public int diameterOfBinaryTree(TreeNode root) {
if (root == null) return 0;
Int ans = new Int(0);
depthOfTree(root, ans);
return ans.val;
}
public int depthOfTree(TreeNode root, Int ans) {
if (root == null) return 0;
int l = depthOfTree(root.left, ans);
int r = depthOfTree(root.right, ans);
ans.val = Math.max(ans.val, l + r);
return 1 + Math.max(l, r);
}
}