104-二叉树的最大深度

/**
二叉树的最大深度:104
2026-10-30 14:12:04
//给定一个二叉树 root ,返回其最大深度。 
//
// 二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。 
//
// 
//
// 示例 1: 
//
// 
//
// 
//
// 
//输入:root = [3,9,20,null,null,15,7]
//输出:3
// 
//
// 示例 2: 
//
// 
//输入:root = [1,null,2]
//输出:2
// 
//
// 
//
// 提示: 
//
// 
// 树中节点的数量在 [0, 10⁴] 区间内。 
// -100 <= Node.val <= 100 
// 
//
// Related Topics 树 深度优先搜索 广度优先搜索 二叉树 👍 2164 👎 0

**/

//leetcode submit region begin(Prohibit modification and deletion)
/**
 * 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 {
    /**
     * 思路: 深度 = 1 + max(左深度, 右深度);
     * 时间复杂度 : O(N)
     * 空间复杂度:O(N)
     * Success:
     *  Runtime:1 ms, faster than 41.82% of Java online submissions.
     *  Memory Usage:46.4 MB, less than 26.44% of Java online submissions.
     * @param root
     * @return
     */
    public int maxDepth(TreeNode root) {
        if(root == null ) {
            return 0;
        } else if(root.left == null && root.right == null) {
            return 1;
        } else  {
            int leftMax = 1 + maxDepth(root.left);
            int rightMax = 1 + maxDepth(root.right);
            return  Math.max(leftMax,rightMax);
        }
    }
}
//leetcode submit region end(Prohibit modification and deletion)

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容