Leetcode 543. Diameter of Binary Tree

 

 

开始耍小聪明啦,getMax是求得深度最大值。我们在diameterOfbinaryTree中不断求得左右子树的直径,相加,并且递归,即可获得最大值

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
        if(!root) return 0;
        return max(max(getMax(root->left) + getMax(root->right), diameterOfBinaryTree(root->left)), diameterOfBinaryTree(root->right));
    }
    int getMax(TreeNode* root) {
        if(!root) return 0;
        return max(getMax(root->left), getMax(root->right)) + 1;
    }
};

 

posted @ 2020-02-07 19:34  SteveYu  阅读(133)  评论(0编辑  收藏  举报