【队列】求二叉树的层序遍历

求解代码

构建一个辅助队列queue,让root首先进入队列。

java 复制代码
public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
        ArrayList<ArrayList<Integer>> ans = new ArrayList<>();

		if(root==null){
			return ans;
		}
		Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
		queue.add(root);

		while(!queue.isEmpty()){
			ArrayList<Integer> list = new ArrayList<>();

			int n = queue.size();

			for(int i=0;i<n;i++){
				TreeNode cur = queue.poll();
				list.add(cur.val);

				if (cur.left!=null) {
					queue.add(cur.left);
				}
				
				if(cur.right!=null){
					queue.add(cur.right);
				}
			}
			ans.add(list);
		}

		return ans;
    }
相关推荐
alphaTao3 小时前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
Cccp.1233 小时前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
Pniubi4 小时前
力扣70爬楼梯
数据结构·算法·leetcode
Navigator_Z19 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil20819 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
Nil20820 小时前
leetcode 72编辑距离
算法·leetcode·职场和发展
Nil20820 小时前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
局部有解1 天前
LeetCode Hot100 438 找到字符串中所有字母异位词
c++·算法·leetcode
Nil2081 天前
leetcode 75颜色分类
数据结构·算法·leetcode
aqiu1111111 天前
CodeTop按顺序刷题0003:LeetCode 206. 反转链表(迭代法图文详解与动态演示)
算法·leetcode·链表