每日一练:LeeCode-102、二又树的层序遍历【二叉树】

本文是力扣LeeCode-102、二又树的层序遍历 学习与理解过程,本文仅做学习之用,对本题感兴趣的小伙伴可以出门左拐LeeCode

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

示例 1:

输入:root = [3,9,20,null,null,15,7]

输出:[[3],[9,20],[15,7]]

示例 2:

输入:root = [1]

输出:[[1]]

示例 3:

输入:root = []

输出:[]

提示:

树中节点数目在范围 [0, 2000]
-1000 <= Node.val <= 1000

思路

层序遍历,符合队列queue 先进先出 的规律:左边先进,左边先出,只要保证从上到下每层遍历即可

代码实现

下列两段代码可以作为BFS模版 解决二叉树层序遍历相关的问题
BFS模版1

java 复制代码
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        
        if(root==null) return res;
        queue.add(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> tempList = new ArrayList<>();
            // 这⾥⼀定要使⽤固定⼤⼩size,不要使⽤que.size(),因为que.size是不断变化的
            for(int i=0;i<size;i++){
                TreeNode node = queue.poll();
                tempList.add(node.val);
                if(node.left!=null)queue.add(node.left);
                if(node.right!=null)queue.add(node.right);
            }
            res.add(tempList);	//每层遍历完,放进结果即可
        }
        return res;
    }
}

BFS模版2

java 复制代码
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root==null){return res;}

        int start = 0; 
        int end = 1; 
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        List<Integer> tempList = new ArrayList<>();
        while(!queue.isEmpty()){
            TreeNode t = queue.poll(); 
            tempList.add(t.val);
            start++;

            if(t.left!=null) queue.add(t.left);
            if(t.right!=null) queue.add(t.right);
            if(start == end){	//某层都遍历完后,才添加结果,并初始化
                res.add(new ArrayList<>(tempList));
                start = 0;
                end = queue.size();
                tempList.clear();
            }
        }
        return res;
    }
}

最重要的一句话:做二叉树的题目,首先需要确认的是遍历顺序
大佬们有更好的方法,请不吝赐教,谢谢

相关推荐
Jasmine_llq14 分钟前
《P3825 [NOI2017] 游戏》
算法·游戏·枚举法·2-sat 算法·tarjan 算法·邻接表存储
Miraitowa_cheems18 分钟前
LeetCode算法日记 - Day 38: 二叉树的锯齿形层序遍历、二叉树最大宽度
java·linux·运维·算法·leetcode·链表·职场和发展
wangzy198218 分钟前
图形基础算法:如何将点与带曲线边的多边形位置关系算法做稳定
算法
艾醒38 分钟前
探索大语言模型(LLM):Ollama快速安装部署及使用(含Linux环境下离线安装)
人工智能·深度学习·算法
艾醒1 小时前
探索大语言模型(LLM):Open-WebUI的安装
人工智能·算法·全栈
猫天意2 小时前
【CVPR2023】奔跑而非行走:追求更高FLOPS以实现更快神经网络
人工智能·深度学习·神经网络·算法·机器学习·卷积神经网络
宁檬精2 小时前
算法练习——55.跳跃游戏
数据结构·算法·游戏
王璐WL2 小时前
【C语言入门级教学】内存函数
c语言·开发语言·算法
啃啃大瓜2 小时前
python常量变量运算符
开发语言·python·算法
熊文豪2 小时前
【华为OD】找出通过车辆最多颜色
算法·华为od