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

求解代码

构建一个辅助队列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;
    }
相关推荐
We་ct1 天前
LeetCode 148. 排序链表:归并排序详解
前端·数据结构·算法·leetcode·链表·typescript·排序算法
x_xbx1 天前
LeetCode:2. 两数相加
算法·leetcode·职场和发展
_日拱一卒1 天前
LeetCode:最长连续序列
算法·leetcode·职场和发展
重生之后端学习1 天前
287. 寻找重复数
数据结构·算法·leetcode·深度优先·图论
实心儿儿1 天前
算法7:两个数组的交集
算法·leetcode·职场和发展
sheeta19981 天前
LeetCode 每日一题笔记 日期:2025.03.19 题目:3212.统计X和Y频数相等的子矩阵数量
笔记·leetcode·矩阵
Storynone1 天前
【Day28】LeetCode:509. 斐波那契数,70. 爬楼梯,746. 使用最小花费爬楼梯
python·算法·leetcode
博风1 天前
算法:双指针解:盛最多水的容器
算法·leetcode
阿Y加油吧1 天前
力扣打卡day05——找到字符串中所有字母异位词、和为K的子数组
leetcode
abant21 天前
leetcode912 排序算法总结
算法·leetcode·排序算法