[leetcode]-543. Diameter of Binary Tree

思路:

diameter保存最大的直径,每次更新该值

depthOfBinary利用分治算法计算树的深度:分解为子问题,分别求得左右子树的深度lDepth,rDepth,两者相加+2就是该节点下的最大直径。

代码:

class Solution {
public:
    int diameter = 0;
    int diameterOfBinaryTree(TreeNode* root) {
        depthOfBinaryTree(root);
        return diameter;
    }
    int depthOfBinaryTree(TreeNode* root){
        if(root == NULL){
            return -1;
        }
        int lDepth = depthOfBinaryTree(root->left);
        int rDepth = depthOfBinaryTree(root->right);
        diameter = max(diameter,lDepth+rDepth+2);
        return max(lDepth, rDepth) + 1;
    }
};



猜你喜欢

转载自blog.csdn.net/ljh0302/article/details/67010293