题目:
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7},
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
思路:
前面做过,用Q, 少一步 reverse 其他相同
Code:
public List<List<Integer>> levelOrder(TreeNode root) {
ArrayList<List<Integer>> al=new ArrayList<List<Integer>>();
ArrayList<Integer> level;
if(root==null) return al;
Queue<TreeNode> q=new LinkedList<TreeNode>();
int countCur=0;
int countLast=1;
q.add(root);
while(!q.isEmpty()){
level=new ArrayList<Integer>();
for(int i=0;i<countLast;i++){
root=q.remove();
level.add(root.val);
if(root.left!=null){
q.add(root.left);
countCur++;
}
if(root.right!=null){
q.add(root.right);
countCur++;
}
}
al.add(level);
countLast=countCur;
countCur=0;
}
return al;
}
备注: