```
public int diameterOfBinaryTree(TreeNode root) {
// passing an array so that it can be modified by reference.
int[] result = {0};
maxDiameter(root, result);
return result[0];
}
private int maxDiameter(TreeNode node, int[] result){
if(node == null){
return 0;
}
int left = maxDiameter(node.left, result);
int right = maxDiameter(node.right, result);
// max of prev diameter or current
result[0] = Math.max(left + right, result[0]);
// contribution of current node to its parent
return Math.max(left, right) + 1;
}
```