题目描述:
代码如下:
/**
* 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;
* }
* }
*/
class Solution { //bfs模板复习!!
public List<List<Integer>> levelOrder(TreeNode root) {
if(root==null){
return new LinkedList<>();
}
List<List<Integer>>res=new LinkedList<>();
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()){
int size=queue.size();
List<Integer> list =new LinkedList<>();
for (int i = 0; i < size; i++) {
TreeNode poll = queue.poll();
list.add(poll.val);
if(poll.left!=null){
queue.add(poll.left);
}
if (poll.right!=null){
queue.add(poll.right);
}
}
res.add(list);
}
return res;
}
}