102. 二叉树的层序遍历 - 力扣(LeetCode) (leetcode-cn.com)
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root==null) return new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>(); //利用队列实现BFS
queue.add(root);
while(!queue.isEmpty()){
List<Integer> tmp = new ArrayList<>();
int count = queue.size();
while(count>0){
TreeNode node = queue.poll();
tmp.add(node.val);
if(node.left!=null) queue.add(node.left);
if(node.right!=null) queue.add(node.right);
count--;
}
res.add(tmp);
}
return res;
}
}