LeetCode 二叉树的最大深度 递归+层序遍历

知识点:

队列先进先出;

queue.offer() 入队;

queue.poll() 出队;

方法一 层序遍历:

每一轮 while 处理一层:先用 size 固定当前层数量,for 只处理这 size 个节点;孩子入队但留到下一轮;for 结束 depth++

java 复制代码
/**
 * 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;
        }
        // 新建一个队列
        Queue<TreeNode> queue=new LinkedList<TreeNode>();
        queue.offer(root);  //根结点入队
        int depth=0;
        while(!queue.isEmpty()){
            int size=queue.size();  //当前层的节点数
            for(int i=0;i<size;i++){
                TreeNode node=queue.poll(); //取出当前层的一个结点
                if(node.left!=null){
                    queue.offer(node.left);  //当前层结点的左孩子
                }
                if(node.right!=null){
                    queue.offer(node.right);  //当前层结点的右孩子
                }

            }
            depth++;
        }
        return depth;
    }
}

方法二:

递归:深度优先遍历

二叉树深度=左右子树深度最大值+1

java 复制代码
class Solution {
    public int maxDepth(TreeNode root) {
       
        if(root==null){
            return 0;
        }else{
            int leftHeight=maxDepth(root.left);
            int rightHeight=maxDepth(root.right);
            return Math.max(leftHeight,rightHeight)+1;
        }
    }
}
相关推荐
小辉同志9 分钟前
207. 课程表
c++·算法·力扣·图论
CheerWWW16 分钟前
深入理解计算机系统——位运算、树状数组
笔记·学习·算法·计算机系统
仟濹23 分钟前
2026-04-09~10-复习计划+蓝桥杯注意的点
职场和发展·蓝桥杯
锅挤1 小时前
数据结构复习(第一章):绪论
数据结构·算法
skywalker_111 小时前
力扣hot100-5(盛最多水的容器),6(三数之和)
算法·leetcode·职场和发展
汀、人工智能1 小时前
[特殊字符] 第95课:冗余连接
数据结构·算法·链表·数据库架构··冗余连接
生信研究猿1 小时前
leetcode 226.翻转二叉树
算法·leetcode·职场和发展
一只小白0001 小时前
反转单链表模板
数据结构·算法
橘颂TA1 小时前
【笔试】算法的暴力美学——牛客 WY22 :Fibonacci数列
算法
XWalnut1 小时前
LeetCode刷题 day9
java·算法·leetcode