LeetCode(66)二叉树的最大深度【二叉树】【简单】

在这里插入图片描述

链接: 二叉树的最大深度

1.题目

给定一个二叉树 root ,返回其最大深度。

二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。

示例 1:

在这里插入图片描述

输入:root = [3,9,20,null,null,15,7]
输出:3

示例 2:

输入:root = [1,null,2]
输出:2

提示:

  • 树中节点的数量在 [0, 10^4] 区间内。
  • -100 <= Node.val <= 100

2.答案

/**
 * 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;
        }
        return handleDepth(root, 0);
    }

    private int handleDepth(TreeNode root, int depth) {
   
        depth++;
        int leftDepth = depth;
        if (root.left != null) {
   
            leftDepth = handleDepth(root.left, depth);
        }
        int rightDepth = depth;
        if (root.right != null) {
   
            rightDepth = handleDepth(root.right, depth);
        }
        return Math.max(leftDepth, rightDepth);
    }
}

3.提交结果截图

在这里插入图片描述

整理完毕,完结撒花~ 🌻

相关推荐

  1. ---深度

    2023-12-17 20:06:02       24 阅读
  2. LeetCode104 深度

    2023-12-17 20:06:02       40 阅读
  3. [leetcode] 104. 深度

    2023-12-17 20:06:02       44 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-17 20:06:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-17 20:06:02       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-17 20:06:02       87 阅读
  4. Python语言-面向对象

    2023-12-17 20:06:02       96 阅读

热门阅读

  1. RHCE 9版本考试资料

    2023-12-17 20:06:02       39 阅读
  2. 如何传承中国文化

    2023-12-17 20:06:02       62 阅读
  3. 面试经典150题(21-26)

    2023-12-17 20:06:02       65 阅读
  4. K8s中Service Account和RBAC

    2023-12-17 20:06:02       50 阅读
  5. Linux Find

    2023-12-17 20:06:02       54 阅读
  6. Spring Boot 自动装配的原理

    2023-12-17 20:06:02       57 阅读
  7. Angular13无法在浏览器debug

    2023-12-17 20:06:02       53 阅读
  8. UI卡顿问题

    2023-12-17 20:06:02       60 阅读
  9. centos7安装和卸载MySQL8.0

    2023-12-17 20:06:02       59 阅读
  10. linux ioctl

    2023-12-17 20:06:02       41 阅读
  11. Logcat日志记录的使用

    2023-12-17 20:06:02       58 阅读
  12. 数据结构之链表篇 单链表 循环链表 双向链表

    2023-12-17 20:06:02       68 阅读