面试算法-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;
    }
}
相关推荐
sel_94 分钟前
【多轮对话论文导读(七)】多轮对话论文阅读笔记:从数据生成、用户模拟到上下文重构与长期记忆
论文阅读·人工智能·笔记·深度学习·算法·语言模型·自然语言处理
远游客07136 分钟前
为什么用「年×100+月」做比较
算法·gin
leavesleo1 小时前
DeepSeek 偷偷给你取外号?拆一下 AI 人格化背后的技术
算法
liliangcsdn1 小时前
skewness收益偏度取负因子背后逻辑的探索
人工智能·算法·机器学习
码匠许师傅1 小时前
【C++ 面试真题】35. 聊聊 C++ 的万能引用(T&&)和完美转发(std::forward)
java·c++·面试
鹿角片ljp1 小时前
LeetCode 300. 最长递增子序列|从 DP O (n²) 到贪心 + 二分 O (n log n)
算法·动态规划
叠层归一研究院1 小时前
缝合维度:时空3+1结构的拓扑起源
人工智能·算法·机器学习·agi
YXXY3132 小时前
FloodFill算法
算法
OPEN-F2 小时前
C++入门教程:数组、字符串与指针入门
数据结构·c++·算法
林森lsjs2 小时前
零基础吃透二叉树:定义、遍历与高频算法 —数据结构柒
java·开发语言·数据结构·算法·二叉树