力扣-二叉树的最大深度

思路分析

  1. 深度优先遍历
  2. 广度优先遍历

代码实现

这两种都是模板代码,这里做记录方便后续回顾

  1. 深度优先遍历
java 复制代码
public int maxDepth(TreeNode root){
   // 递归结束条件
    if(root == null) return 0;
    // 递归遍历左子树
    int left = maxDepth(root.left);
    // 递归遍历右子树
    int right = maxDepth(root.right);

    return Math.max(left, right) + 1;
}
  1. 广度优先遍历
java 复制代码
public int maxDepth2(TreeNode root){
   Queue<TreeNode> queue = new ArrayDeque<>();
    // 根节点入队
    if(root != null) queue.offer(root);
    int level = 0;
    // 队非空时
    while (!queue.isEmpty()){
        // 获取当前队列长度
        int size = queue.size();
        // 遍历队列中当前层级节点
        while(size > 0){
            // 出队
            TreeNode poll = queue.poll();
            // 左节点入队
            if (poll.left != null) {
                queue.offer(poll.left);
            }
            // 右节点入队
            if (poll.right != null) {
                queue.offer(poll.right);
            }
            --size;
        }
        // 层级加一
        ++level;
    }
    return level;
}

复杂度分析

相关推荐
早点睡觉好了15 分钟前
重排序 (Re-ranking) 算法详解
算法·ai·rag
gihigo199818 分钟前
基于全局自适应动态规划(GADP)的MATLAB实现方案
算法
ctyshr1 小时前
C++编译期数学计算
开发语言·c++·算法
zh_xuan1 小时前
最小跳跃次数
数据结构·算法
yumgpkpm2 小时前
2026软件:白嫖,开源,外包,招标,晚进场(2025年下半年),数科,AI...中国的企业软件产业出路
大数据·人工智能·hadoop·算法·kafka·开源·cloudera
孞㐑¥2 小时前
算法—队列+宽搜(bfs)+堆
开发语言·c++·经验分享·笔记·算法
yufuu982 小时前
并行算法在STL中的应用
开发语言·c++·算法
zh_xuan2 小时前
单青蛙跳台阶
数据结构·算法
Kx_Triumphs2 小时前
计算几何-旋转卡壳两种实现方案(兼P1452题解
算法·题解
代码游侠2 小时前
学习笔记——Linux字符设备驱动开发
linux·arm开发·驱动开发·单片机·嵌入式硬件·学习·算法