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;
        }
    }
}
相关推荐
爱读书的小胖21 分钟前
LeetCode 122:买卖股票的最佳时机 II(C)解题分析
算法
结局无敌22 分钟前
React Native for OpenHarmony 实战:三方库 react-native-modal-dialog 的鸿蒙化适配指南
深度学习·算法·react native·react.js·harmonyos
ychqsq39 分钟前
234.无题
经验分享·职场和发展
OPEN-F1 小时前
ROS2系列教程:上位机建图与导航(原理综合)
算法·机器人
weixin_307779131 小时前
C++代码实现MATLAB中的fitrtree函数功能
开发语言·c++·算法·matlab
tomwang03221 小时前
路径优化建模、优化算法分类及工程化小结
算法·数学建模·分类
小羊没烦恼!1 小时前
Ajax与JSON的一些总结
android·java·前端·数据库·mysql·算法·okhttp
考研保研资料分享1 小时前
物理保研至中科大:固体物理复习、四场面试与科研追问
面试·职场和发展
2501_926978331 小时前
人机通信协议--人和机器之间的交互想象
人工智能·经验分享·算法·ai写作
行者全栈架构师1 小时前
【鸿蒙心迹】互动卡片全链路——把核心功能放到桌面(FormKit 实战)(HarmonyOS 7.x)
前端·算法·架构