面试算法-66-二叉树的层序遍历

题目

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

示例 1:

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

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

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

        LinkedList<TreeNode> queue = new LinkedList<>();
        LinkedList<TreeNode> queue2 = new LinkedList<>();
        queue.offer(root);
        List<Integer> res = new ArrayList<>();
        while (!queue.isEmpty()) {
            TreeNode poll = queue.poll();
            res.add(poll.val);
            if (poll.left != null) {
                queue2.offer(poll.left);
            }
            if (poll.right != null) {
                queue2.offer(poll.right);
            }
            if (queue.isEmpty()) {
                result.add(res);
                res = new ArrayList<>();
                queue = queue2;
                queue2 = new LinkedList<>();
            }
        }
        return result;
    }
}
相关推荐
体系结构论文研讨会27 分钟前
多项式环及Rq的含义
算法
智驱力人工智能36 分钟前
极端高温下的智慧出行:危险检测与救援
人工智能·算法·安全·行为识别·智能巡航·高温预警·高温监测
旷世奇才李先生39 分钟前
奇哥面试记:SpringBoot整合RabbitMQ与高级特性,一不小心吊打面试官
spring boot·面试·java-rabbitmq
森焱森44 分钟前
60 美元玩转 Li-Fi —— 开源 OpenVLC 平台入门(附 BeagleBone Black 驱动简单解析)
c语言·单片机·算法·架构·开源
mrsk1 小时前
🧙‍♂️ CSS中的结界术:BFC如何拯救你的布局混乱?
前端·css·面试
程序员清风1 小时前
程序员要在你能挣钱的时候拼命存钱!
后端·面试·程序员
课堂剪切板2 小时前
ch07 题解
算法·深度优先
June bug2 小时前
【Python基础】变量、运算与内存管理全解析
开发语言·python·职场和发展·测试
_一条咸鱼_2 小时前
Vulkan入门教程:源码级解析
android·面试·android jetpack
前端小巷子2 小时前
深入解析CSRF攻击
前端·安全·面试