leetcode 543. Diameter of Binary Tree

来源:互联网 发布:网络维护维修预算 编辑:程序博客网 时间:2024/06/08 04:10

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);
    }
};

0 0
原创粉丝点击