codeTop102:二叉树的层序遍历

前言

在已知BFS的方式后,知道每次从队列中取一个节点,就要将这个节点的所有子节点按照顺序放入队列。

难点在于怎么确定将同一层的节点放在一个数组里面的输出,也就是输出一个二维数组?

解决方法:

每次while循环将队列上轮放入的节点全部取出(之前的普通BFS是每次whie循环只取一个节点)。

java 复制代码
 public  List<List<Integer>> levelOrder(TreeNode root) {
    List<List<Integer>> res = new ArrayList<>();
    if (root == null){
        return res;
    }
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(root);

    while (!queue.isEmpty()){

        int size = queue.size();
        List<Integer> temp = new ArrayList<>();
        for (int i = 0 ; i < size; i++ ){
            TreeNode target = queue.poll();
            temp.add(target.val);

            if (target.left != null){
                queue.add(target.left);
            }

            if (target.right != null){
                queue.add(target.right);
            }
        }

        res.add(temp);

    }

   return res;
}

相关推荐
std860211 小时前
微软解除 Win11 限制,“毛玻璃”效果将无处不在
windows
csdn_aspnet1 小时前
如何在 Mac、Ubuntu、CentOS、Windows 上安装 MySQL 客户端
linux·windows·mysql·macos·centos
24kHT1 小时前
conda以及Jupyter notebook的使用
windows·jupyter·conda
alphaTao9 小时前
LeetCode 每日一题 2025/11/3-2025/11/9
windows·leetcode
习惯就好zz16 小时前
WSL2 安装Ubuntu卡在安装进度0%无响应问题解决
linux·windows·ubuntu·wsl·wsl2
仰望—星空19 小时前
MiniEngine学习笔记 : CommandListManager
c++·windows·笔记·学习·cg·direct3d
ue星空1 天前
Windows内核函数使用
windows
业余幻想家1 天前
Windows10/Windows11家庭版系统关闭自动更新
运维·windows
阿猿收手吧!1 天前
windows本机vscode通过ssh免密登录远程linux服务器 && git push/pull 免密
服务器·windows·vscode
zxm85131 天前
如何在Windows系统中加入程序自启动
windows