2025年- G23-Lc97-104.二叉树的最大深度-java版(递归调用左右子树)
1.题目描述

2.思路
要用到max函数,返回的时候返回左右子树的最大值。其次要递归调用左右子树,寻找最大深度。
 在每个递归返回时,我们 必须把当前节点的深度算进去,否则我们只计算了子树的深度,而没有包括当前节点。
3.代码实现
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null)
        {
            return 0;// 空节点深度为 0
        }
        int rightDepth=maxDepth(root.right);// 计算左子树深度
        int leftDepth=maxDepth(root.left);// 计算右子树深度
        return  Math.max(rightDepth,leftDepth)+1;// 取最大值 +1(加上当前层)
        
        
    }
}
