[leetcode] 543. Diameter of Binary Tree (easy)

原题

思路:
题目其实就是求左右最长深度的和

class Solution
{
  private:
    int res = 0;

  public:
    int diameterOfBinaryTree(TreeNode *root)
    {
        dfs(root);
        return res;
    }

    int dfs(TreeNode *root)
    {
        if (root == NULL)
        {
            return 0;
        }
        int leftNum = dfs(root->left);
        int rightNum = dfs(root->right);
        res = max(res, leftNum + rightNum);
        return max(leftNum, rightNum) + 1;
    }
};
posted @ 2018-09-30 08:58  Ruohua3kou  阅读(111)  评论(0编辑  收藏  举报