递归查找二叉树深度

1

public static int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        // 递归计算左子树和右子树的深度
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        
        // 最大深度为左子树和右子树深度的最大值加1
        return Math.max(leftDepth, rightDepth) + 1;
    }

 

 
posted @ 2024-08-14 15:31  抽象Java  阅读(2)  评论(0编辑  收藏  举报