解题思路:层级遍历
1.在每一层中,遍历该层所有节点,并将节点的值存放到ArrayList中,然后加入到res中
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root==null){
return new ArrayList<>();
}
Queue<TreeNode> queue=new LinkedList<>();
List<Integer> list;
List<List<Integer>> res = new ArrayList<>();
queue.add(root);
while(!queue.isEmpty()){
int levelNum=queue.size();
list=new ArrayList<>();
for(int i=0;i<levelNum;i++){
TreeNode node=queue.poll();
list.add(node.val);
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
}
res.add(list);
}
return res;
}
}