
class Solution {
public:
int ans=INT_MIN;
int dfs(TreeNode*root){
if(!root)return 0;
int l=dfs(root->left);
int r=dfs(root->right);
ans=max(ans,l+r+1);
return max(l,r)+1;
}
int diameterOfBinaryTree(TreeNode* root) {
dfs(root);
return ans-1;
}
};
原创
leetcode543. 二叉树的直径
本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。