力扣-二叉树的最大深度

思路分析

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

复杂度分析

相关推荐
freexyn13 分钟前
Matlab入门自学七十四:坐标系转换,直角坐标、极坐标和球坐标的转换
开发语言·算法·matlab
咱就是说不配啊20 分钟前
3.20打卡day34
数据结构·c++·算法
小张会进步25 分钟前
数组:二维数组
java·javascript·算法
佑白雪乐43 分钟前
LCR 175. 计算二叉树的深度
算法·深度优先
阿Y加油吧1 小时前
力扣打卡day07——最大子数组和、合并区间
算法
想吃火锅10051 小时前
【leetcode】105. 从前序与中序遍历序列构造二叉树
算法·leetcode·职场和发展
圣保罗的大教堂1 小时前
leetcode 3567. 子矩阵的最小绝对差 中等
leetcode
2401_831824961 小时前
嵌入式C++驱动开发
开发语言·c++·算法
靠沿1 小时前
【优选算法】专题十八——BFS解决拓扑排序问题
算法·宽度优先
cui_ruicheng1 小时前
C++数据结构进阶:哈希表实现
数据结构·c++·算法·哈希算法·散列表