Run DFS to compute depth at each node. Track the maximum of leftDepth + rightDepth across all nodes.
Here's the solution:
function diameterOfBinaryTree(root):
maxDiameter = 0
function depth(node):
if node is null:
return 0
left = depth(node.left)
right = depth(node.right)
maxDiameter = max(maxDiameter, left + right)
return 1 + max(left, right)
depth(root)
return maxDiameter
time, space where is the tree height.