leetcode刷题(剑指offer) 102.二叉树的层序遍历

102.二叉树的层序遍历

给你二叉树的根节点 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

本题是要层级遍历二叉树,将每层的所有节点都存入到list中。主要存在两个需要解决的点。

  • 如何层级遍历二叉树
  • 如何知道每层有哪些节点

接替围绕着这两个点,首先可以使用队列来层级遍历每个节点,思路类似于宽度优先搜索(bfs),先将root节点放入队列中,每次都弹出队头节点,取出节点,然后将取出节点的left节点和right节点依次放入到队列中,直到没有节点再能放入到队列中为止(即:队列为空)。

随后再此基础上,创建变量lastNode表示为当前层的最后一个节点,nextLastNode表示为下一层的最后一个节点,这个变量每次从队列中取出节点都会进行更新,当弹出节点等于lastNode时,即可将一层的list存入总的list,且将lastNode更新为nextLastNode

代码实现如下:

java 复制代码
public static List<List<Integer>> levelOrder(TreeNode root) {
    if (root == null) {
        return new ArrayList<>();
    }
    List<List<Integer>> res = new ArrayList<>();
    TreeNode lastNode = root;
    TreeNode nextLastNode = null;
    Queue<TreeNode> queue = new ArrayDeque<>();
    List<Integer> list = new ArrayList<>();
    queue.add(root);
    while (!queue.isEmpty()) {
        TreeNode node = queue.poll();
        list.add(node.val);
        if (node.left != null) {
            nextLastNode = node.left;
            queue.add(node.left);
        }
        if (node.right != null) {
            nextLastNode = node.right;
            queue.add(node.right);
        }
        if (lastNode == node) {
            res.add(list);
            list = new ArrayList<>();
            lastNode = nextLastNode;
        }

    }
    return res;
}
相关推荐
IronMurphy44 分钟前
【算法四十三】279. 完全平方数
算法
墨染天姬1 小时前
【AI】Hermes的GEPA算法
人工智能·算法
有谁看见我的剑了?1 小时前
linux 添加硬盘后系统识别不到硬盘处理
linux·运维·服务器
papership1 小时前
【入门级-数据结构-3、特殊树:完全二叉树的数组表示法】
数据结构·算法·链表
smj2302_796826521 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
Beginner x_u2 小时前
链表专题:JS 实现原理与高频算法题总结
javascript·算法·链表
yc_12242 小时前
用 Visual Studio 远程调试 Linux:从零到流畅的完整指南
linux·ide·visual studio
计算机安禾3 小时前
【Linux从入门到精通】第31篇:防火墙漫谈——iptables与firewalld防护指南
linux·运维·php
下一页盛夏花开3 小时前
ubuntu 20中安装QT以后出现红色空心断点
linux·运维·ubuntu
sanshanjianke4 小时前
Thunderobot 911ME 笔记本 Linux 风扇控制研究
linux