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

题目

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

示例 1:
在这里插入图片描述

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

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        return bfs(root);
    }

    public List<List<Integer>> bfs(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }

        LinkedList<TreeNode> queue1 = new LinkedList<>();
        LinkedList<TreeNode> queue2 = new LinkedList<>();
        queue1.add(root);
        List<Integer> list = new ArrayList<>();
        while (!queue1.isEmpty()) {
            TreeNode poll = queue1.poll();
            list.add(poll.val);
            if (poll.left != null) {
                queue2.add(poll.left);
            }
            if (poll.right != null) {
                queue2.add(poll.right);
            }

            if (queue1.isEmpty()) {
                result.add(list);
                list = new ArrayList<>();
                queue1 = queue2;
                queue2 = new LinkedList<>();
            }
        }
        return result;
    }
}

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-22 20:46:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-22 20:46:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-22 20:46:02       82 阅读
  4. Python语言-面向对象

    2024-04-22 20:46:02       91 阅读

热门阅读

  1. ERESOLVE overriding peer dependency npm install错误

    2024-04-22 20:46:02       35 阅读
  2. ChatGPT改写:论文写作新时代

    2024-04-22 20:46:02       40 阅读
  3. LeetCode49字母异位词分组

    2024-04-22 20:46:02       32 阅读
  4. 【JVM】JVM的垃圾回收机制与垃圾回收器的选择

    2024-04-22 20:46:02       34 阅读
  5. 从安装系统到部署datax

    2024-04-22 20:46:02       40 阅读
  6. CS32 C++ programming

    2024-04-22 20:46:02       32 阅读
  7. LeetCode-94-二叉树的中序遍历

    2024-04-22 20:46:02       27 阅读
  8. springboot接口提高查询速度方法

    2024-04-22 20:46:02       39 阅读
  9. 分治法构建Gray码问题

    2024-04-22 20:46:02       34 阅读
  10. 深入理解与运用Vue 2中的插槽(Slots)

    2024-04-22 20:46:02       35 阅读
  11. 测试testing1

    2024-04-22 20:46:02       29 阅读
  12. Mysql多表联查使用聚合函数常见问题

    2024-04-22 20:46:02       30 阅读