LeetCode hot100——二叉树的最大深度

题目

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

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

示例 1:

复制代码
输入:root = [3,9,20,null,null,15,7]
输出:3

示例 2:

复制代码
输入:root = [1,null,2]
输出:2

提示:

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

题解

题解一(DFS后序遍历)
复制代码
/**
 * 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 Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
    }
}
题解二(BFS层序遍历)
复制代码
/**
 * 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;

        List<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        List<TreeNode> tmp = new LinkedList<>();
        int res = 0;

        while (!queue.isEmpty()) {
            tmp = new LinkedList<>();
            for(TreeNode node : queue) {
                if (node.left != null) tmp.add(node.left);
                if (node.right != null) tmp.add(node.right);
            }
            queue = tmp;
            res++;
        }
        return res;
    }
}
相关推荐
文丑颜不良啊7 小时前
LeetCode3061~3080题目解析
java·leetcode
电科_银尘9 小时前
【大模型算法与工程 01】机器学习的问题定义:监督、无监督、自监督与强化学习
人工智能·算法·机器学习
文丑颜不良啊9 小时前
LeetCode3081~3100题目解析
java·leetcode
电科_银尘10 小时前
【大模型算法与工程 05】分类、回归与排序指标:怎样评价一个模型
算法·分类·回归
文丑颜不良啊21 小时前
LeetCode2981~3000题目解析
java·leetcode
罗西的思考1 天前
【轻量化复刻大模型 / KIMI K3】Multi-Token Prediction(MTP / EAGLE-3)(2)
人工智能·算法·机器学习
罗西的思考1 天前
【轻量化复刻大模型 / KIMI K3】Multi-Token Prediction(MTP / EAGLE-3)(1)
人工智能·算法·机器学习
武子康1 天前
H3-World 接入 Game Agent:谁来判断门真的打开了?
人工智能·算法·机器学习
文丑颜不良啊1 天前
LeetCode3001~3020题目解析
java·leetcode
武子康1 天前
H3-World 扩展跳跃与开门:新动作怎样进入训练数据?
大数据·人工智能·算法