Leetcode 102.二叉树的层次遍历

题目

image-20240325163938550

思路

利用一个队列来辅助进行层序遍历

口诀:入队出队访问,有左入左,有右入右。这样方便记忆。具体位置请看代码注释。

因为题目要求把一层的输出到一个list里。所以我们要在while(!queue.isEmpty()) 循环一开始设置一个len表示这一层中有几个节点。

代码

//leetcode submit region begin(Prohibit modification and deletion)

import java.util.ArrayList;
import java.util.LinkedList;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (root == null)
            return res;

        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);  //入队
        while (!queue.isEmpty()) {
            List<Integer> item = new ArrayList<Integer>();
            int len = queue.size();
            while (len > 0) {
                TreeNode temp = queue.poll(); //出队
                item.add(temp.val); //访问
                if (temp.left != null) //有左入左
                    queue.add(temp.left);
                if (temp.right != null) //有右入右
                    queue.add(temp.right);
                len--;
            }
            res.add(item);
        }
        return res;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

相关推荐

  1. Leetcode 102层次

    2024-03-29 13:14:02       31 阅读
  2. Leetcode 107层次II

    2024-03-29 13:14:02       32 阅读
  3. leetcode 102.层序

    2024-03-29 13:14:02       48 阅读
  4. LeetCode102. 层序

    2024-03-29 13:14:02       24 阅读

最近更新

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

    2024-03-29 13:14:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-29 13:14:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-29 13:14:02       82 阅读
  4. Python语言-面向对象

    2024-03-29 13:14:02       91 阅读

热门阅读

  1. python面试题(36~50)

    2024-03-29 13:14:02       45 阅读
  2. day 1 HTTP基础

    2024-03-29 13:14:02       43 阅读
  3. 关闭Qt在windows上同时生成debug和release目录

    2024-03-29 13:14:02       35 阅读
  4. npm insall报错无效的依赖类型:别名(alias)

    2024-03-29 13:14:02       41 阅读
  5. C++原创2D我的世界1.00.3 QPBSv01测试版

    2024-03-29 13:14:02       32 阅读
  6. python 之 常见错误信息

    2024-03-29 13:14:02       42 阅读
  7. pytorch中torch.stack()用法虽简单,但不好理解

    2024-03-29 13:14:02       36 阅读