面试算法-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;
    }
}
相关推荐
开开心心就好26 分钟前
电脑禁止自动休眠工具,还能按负载定时
算法·智能手机·pdf·电脑·word·音视频·lua
apcipot_rain1 小时前
数据开发 面试 xhs面经解答合集
面试·职场和发展
geovindu12 小时前
python:DecisionTree
开发语言·后端·python·算法
Cosolar12 小时前
从 Java 21 升到 25、Spring Boot 3 升 4:一次可复现的迁移踩坑实录
java·后端·面试
ShineWinsu13 小时前
对于Qt:事件的解析
c++·qt·面试·笔试·gui·客户端·事件
geovindu14 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
AIHR数智引擎14 小时前
拆掉“关键人依赖”:黄仁勋复职全员会上的四道组织切口
人工智能·经验分享·职场和发展·ai-native·英伟达·aihr
我叫黑大帅16 小时前
搜“张三”把备注也带出来了?不用加高级筛选,如何让一个搜索框实现「选项直达」!
前端·javascript·面试
AllData公司负责人16 小时前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris