Use **DFS** to compute the depth of each node. In each recursion, **backtrack** and update the diameter in realtime.

```
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
int result = 0;
depth(root, result);
return result;
}
int depth(TreeNode* node, int& diameter) {
if (!node) return 0;
int left = depth(node->left, diameter);
int right = depth(node->right, diameter);
diameter = max(diameter, left + right);
return max(left, right) + 1;
}
};
```