力扣-二叉树的最大深度

思路分析

  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;
}

复杂度分析

相关推荐
IronMurphy5 分钟前
【算法四十三】279. 完全平方数
算法
墨染天姬11 分钟前
【AI】Hermes的GEPA算法
人工智能·算法
papership30 分钟前
【入门级-数据结构-3、特殊树:完全二叉树的数组表示法】
数据结构·算法·链表
smj2302_7968265234 分钟前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
Beginner x_u1 小时前
链表专题:JS 实现原理与高频算法题总结
javascript·算法·链表
_深海凉_4 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
踩坑记录5 小时前
leetcode hot100 寻找两个正序数组的中位数 hard 二分查找 双指针
leetcode
旖-旎5 小时前
深搜练习(电话号码字母组合)(3)
c++·算法·力扣·深度优先遍历
谭欣辰5 小时前
C++快速幂完整实战讲解
算法·决策树·机器学习
Mr_pyx5 小时前
【LeetHOT100】随机链表的复制——Java多解法详解
算法·深度优先