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

求解代码

构建一个辅助队列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;
    }
相关推荐
Adios7944 小时前
设置交集大小至少为2
数据结构·算法·leetcode
程序猿乐锅13 小时前
【数据结构与算法 | 第六篇】力扣1109,1094差分数组
java·算法·leetcode
hold?fish:palm16 小时前
9 找到字符串中所有字母异位词
c++·算法·leetcode
Sw1zzle17 小时前
算法入门(六):贪心算法 - 基础入门(Leetcode 121/455/860/376/738)
算法·leetcode·贪心算法
青山木17 小时前
Hot 100 --- 岛屿数量
java·数据结构·算法·leetcode·深度优先·广度优先
啦啦啦啦啦zzzz17 小时前
算法:回溯算法
c++·算法·leetcode
小肝一下20 小时前
3. 单链表
c语言·数据结构·c++·算法·leetcode·链表·dijkstra
tachibana220 小时前
hot100 前 K 个高频元素(347)
java·数据结构·算法·leetcode
To_OC1 天前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
旖-旎1 天前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题