点击打开链接
//树的直径, 就是在树的最大深度上,加了个 res= max(res, left+right)
class Solution {
public:
int maxDepth(TreeNode* node, int& res)
{
if(!node) return 0;
int left = maxDepth(node->left, res);
int right = maxDepth(node->right, res);
res = max(res, left+right);
return max(left, right)+1;
}
int diameterOfBinaryTree(TreeNode* root) {
int res = 0;
maxDepth(root, res);
return res;
}
};