每日一练: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;
    }
}

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

相关推荐
阳洞洞10 分钟前
二叉树的层序遍历
数据结构·算法·leetcode·二叉树遍历·广度优先搜索
今天也要早睡早起11 分钟前
代码随想录算法训练营Day32| 完全背包问题(二维数组 & 滚动数组)、LeetCode 518 零钱兑换 II、377 组合总数 IV、爬楼梯(进阶)
数据结构·c++·算法·leetcode·动态规划·完全背包
字节旅行者26 分钟前
C++中如何使用STL中的list定义一个双向链表,并且实现增、删、改、查操作
开发语言·数据结构·c++·链表
LLLLLindream39 分钟前
数据结构之链表
数据结构·链表
火车叼位1 小时前
初中生也能懂的贝叶斯定理:拆解一个改变世界的公式
人工智能·数学·算法
ChoSeitaku1 小时前
NO.66十六届蓝桥杯备战|基础算法-贪心-区间问题|凌乱的yyy|Rader Installation|Sunscreen|牛栏预定(C++)
c++·算法·蓝桥杯
用手码出世界1 小时前
二叉树——队列bfs专题
数据结构·算法·宽度优先
OneQ6661 小时前
C++自学笔记---指针在数组遍历中的应用
c++·笔记·算法
EnigmaCoder1 小时前
蓝桥杯刷题周计划(第四周)
c++·算法·蓝桥杯
绿水毛怪.1 小时前
蓝桥杯基础算法-字符串与集合
算法·职场和发展·蓝桥杯