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

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

相关推荐
写代码的小球1 小时前
求模运算符c
算法
雾里看山3 小时前
顺序表VS单链表VS带头双向循环链表
数据结构·链表
大千AI助手5 小时前
DTW模版匹配:弹性对齐的时间序列相似度度量算法
人工智能·算法·机器学习·数据挖掘·模版匹配·dtw模版匹配
好好研究6 小时前
学习栈和队列的插入和删除操作
数据结构·学习
YuTaoShao6 小时前
【LeetCode 热题 100】48. 旋转图像——转置+水平翻转
java·算法·leetcode·职场和发展
生态遥感监测笔记7 小时前
GEE利用已有土地利用数据选取样本点并进行分类
人工智能·算法·机器学习·分类·数据挖掘
Tony沈哲7 小时前
macOS 上为 Compose Desktop 构建跨架构图像处理 dylib:OpenCV + libraw + libheif 实践指南
opencv·算法
刘海东刘海东8 小时前
结构型智能科技的关键可行性——信息型智能向结构型智能的转变(修改提纲)
人工智能·算法·机器学习
pumpkin845148 小时前
Rust 调用 C 函数的 FFI
c语言·算法·rust