力扣 二叉树 104. 二叉树的最大深度

104. 二叉树的最大深度

一、题目描述

二、理解

对照二叉树的递归定义:

  • 如果树为空,则它是一个空树。
  • 如果树不为空,它由一个根节点和两个子树组成,分别是左子树和右子树,且左子树和右子树本身也是二叉树。
    采用递归形式解决问题:
  • 首先判断 root 是否 null,若为 null,则该树的的深度为0。
  • 若 root 不为 null,则该树的最大深度为,max (左子树的最大深度, 右子树最大深度) + 1。

三、代码

java 复制代码
/**
 * 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;
        }
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        return Math.max(leftDepth, rightDepth) + 1;
    }
}
相关推荐
Tim_1019 小时前
【LeetCode】338、比特位计数
c++·算法·leetcode
木子算法19 小时前
不是重心也不是中点:费马—韦伯点、它的最优性条件与迭代求解
人工智能·算法·目标跟踪
2401_8322981020 小时前
人机协同:AI时代全新工作与学习范式
职场和发展
童园管理札记20 小时前
从政策驱动到课堂落地:2026年“人工智能+教育”全景解读与技术实践指南
人工智能·python·深度学习·职场和发展·学习方法
tryxr20 小时前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_320 小时前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Selvaggia20 小时前
DMD(Distribution Matching Distillation,分布匹配蒸馏)
算法
Navigator_Z21 小时前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.21 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
开开心心就好21 小时前
安卓手写文字生成工具,多种纸张一直免费
网络·网络协议·tcp/ip·leetcode·智能手机·电脑·模拟退火算法