力扣-二叉树的最大深度

思路分析

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

复杂度分析

相关推荐
稚南城才子,乌衣巷风流1 小时前
ST 表(Sparse Table)算法详解:原理、实现与应用
算法
hold?fish:palm2 小时前
9 找到字符串中所有字母异位词
c++·算法·leetcode
Sw1zzle2 小时前
算法入门(六):贪心算法 - 基础入门(Leetcode 121/455/860/376/738)
算法·leetcode·贪心算法
青山木2 小时前
Hot 100 --- 岛屿数量
java·数据结构·算法·leetcode·深度优先·广度优先
不会就选b2 小时前
算法日常・每日刷题--<归并排序>1
数据结构·算法
危桥带雨3 小时前
排序算法(快排、归并、计数、基数排序)
数据结构·算法·排序算法
啦啦啦啦啦zzzz3 小时前
算法:回溯算法
c++·算法·leetcode
IT探索3 小时前
Linux 查找文件指令总结
linux·算法
攻城狮Soar3 小时前
C++子类访问父类成员
c++·算法