思路:这一题需要每一行的元素在一起输出。可以使用队列来记录,队列的长度为该行元素的个数(n)。循环n次,为一行。把该行元素存入temp的集合中,循环结束加入list当中。判断如果队列不为空,那么开启下一次循环,新建一个temp集合,继续循环队列的长度n次。把元素放入temp集合当中。直到队列为空,说明所有元素都被遍历了。
写代码的时候遇到了一个容易被忽视的点:我想在前面把temp建好,每次temp.clear(),把集合清空再循环。这里很容易想错,每一个循环中temp都指向一个地址,实际上前面会被后面的temp覆盖。想要这么使用就要在加入list的时候使用(ArrayList)temp.clone()。
/**
* 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>> list =new ArrayList<>();
Queue<TreeNode> que = new LinkedList<>();
if(root==null){
return list;
}
que.add(root);
while(que.size()!=0){
int count=que.size();
ArrayList<Integer> temp = new ArrayList<>();
for(int i=0;i<count;i++){
TreeNode node=que.remove();
temp.add( node.val);
if(node.left!=null){
que.add(node.left);
}
if(node.right!=null){
que.add(node.right);
}
}
list.add(temp);
}
return list;
}
}