文章
99
粉丝
120
获赞
8
访问
98.3k
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int ans = 0;
int dfs(TreeNode *u){
if(u==nullptr)return 0;
int l = dfs(u->left);
int r = dfs(u->right);
ans = max(ans, l+r+1);
return max(l,r)+1;
}
int diameterOfBinaryTree(TreeNode* root) {
dfs(root);
return ans-1;
}
};
登录后发布评论
暂无评论,来抢沙发