注意层序遍历的时候对每一层的处理方式可能不同,这里把每一层的元素保存进一个List
public List<List<Integer>> search(TreeNode root){
List<List<Integer>> result = new ArrayList<List<Integer>>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
if (root == null) {
return result;
}
queue.offer(root);
while(!queue.isEmpty()){
List<Integer> row = new ArrayList<Integer>();
int size = queue.size();
for(int i=0; i<size; i++){
TreeNode now = queue.poll();
row.add(now.val);
if(now.left != null)queue.offer(now.left);
if(now.right != null)queue.offer(now.right);
}
result.add(row);
}
return result;
}