【LeetCode】二叉树的直径

题目描述:

https://leetcode-cn.com/problems/diameter-of-binary-tree/

解题思路:

左子树的深度加上右子树的深度就是通过该节点的直径;
找出其中节点的直径的最大值;

代码:

class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
        int m=0;
        maxPath(root, m);
        return m;
    }
    int maxPath(TreeNode* root, int& m)
    {
        if(!root)
            return 0;
        int left_height = maxPath(root->left, m);
        int right_height = maxPath(root->right, m);
        m = max(m, left_height+right_height);
        return max(left_height, right_height)+1;
        
    }
};

你可能感兴趣的:(【LeetCode】二叉树的直径)