力扣递归之 543. 二叉树的直径

class Solution {
// 二叉树直径 其实就是根到左子树最深+根到右子树最深
    int diameter;
   
    public int diameterOfBinaryTree(TreeNode root) {
        calculateDepth(root);
        return diameter;
    }
   
    private int calculateDepth(TreeNode node) {
        if (node == null) {
            return 0;
        }
       
        int leftDepth = calculateDepth(node.left);
        int rightDepth = calculateDepth(node.right);
       
        diameter = Math.max(diameter, leftDepth + rightDepth);
       
        return Math.max(leftDepth, rightDepth) + 1;
    }
}
posted @ 2024-02-16 20:46  予真  阅读(2)  评论(0编辑  收藏  举报