leetcode 543. Diameter of Binary Tree
一.这道题考察的是对题目的理解,主要是最长路径不一定是经过根的。也就是树的diameter为
max(左子树的diameter,右子树的diameter,左子树深度+右子树深度) 注意路径长度是边的数量,所以max的最后一项不要加1
二. 其实真不简单。 难的是思路。题目tag竟然写easy好伤心。。
三.代码
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
int lmax;
int rmax;
int lrmax;
int ldepth;
int rdepth;
if(!root)
return 0;
lmax = diameterOfBinaryTree(root->left);
rmax = diameterOfBinaryTree(root->right);
lrmax = max(lmax,rmax);
ldepth = depth(root->left);
rdepth = depth(root->right);
return max(lrmax,ldepth+rdepth);
}
int depth(TreeNode *root) //求树的深度
{
if(!root)
return 0;
return (max(depth(root->left),depth(root->right))+1);
}
};