在层序遍历的基础上,每一层单独循环
/**
* 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) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while(!q.isEmpty()){
List<Integer> tmp = new ArrayList<>();
int size = q.size();
for(int i=0; i<size; i++){
TreeNode tree = q.poll();
tmp.add(tree.val);
if(tree.left != null) q.offer(tree.left);
if(tree.right != null) q.offer(tree.right);
}
res.add(tmp);
}
return res;
}
}