题目
链接
题解
/**
* 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;
* }
* }
*/
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) {
return new ArrayList<>(0);
}
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
// 外层循环:每次循环都是一层
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> floor = new ArrayList<>(size);
// 内层循环:每次循环都是一层中的一个节点
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
floor.add(node.val);
// 遍历同层节点时将当前节点的子节点扔进队列
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
// 一层结束后,将层放入答案
res.add(floor);
}
return res;
}
}