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;
        }
    }
}
相关推荐
执风挽^13 分钟前
Python基础编程题2
开发语言·python·算法·visual studio code
Z9fish23 分钟前
sse哈工大C语言编程练习20
c语言·开发语言·算法
晓131328 分钟前
第六章 【C语言篇:结构体&位运算】 结构体、位运算全面解析
c语言·算法
iAkuya34 分钟前
(leetcode)力扣100 61分割回文串(回溯,动归)
算法·leetcode·职场和发展
梵刹古音37 分钟前
【C语言】 指针与数据结构操作
c语言·数据结构·算法
VT.馒头42 分钟前
【力扣】2695. 包装数组
前端·javascript·算法·leetcode·职场和发展·typescript
源代码•宸1 小时前
大厂技术岗面试之谈薪资
经验分享·后端·面试·职场和发展·golang·大厂·职级水平的薪资
马猴烧酒.2 小时前
【面试八股|JVM虚拟机】JVM虚拟机常考面试题详解
jvm·面试·职场和发展
CoderCodingNo2 小时前
【GESP】C++五级练习题 luogu-P1865 A % B Problem
开发语言·c++·算法
大闲在人2 小时前
7. 供应链与制造过程术语:“周期时间”
算法·供应链管理·智能制造·工业工程