题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > result = new ArrayList<>();
if(pRoot==null){
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(pRoot);
boolean isLeft = true;
while(!queue.isEmpty()){
int count = queue.size();
ArrayList<Integer> list = new ArrayList<>();
for(int i = 0; i<count; i++){
TreeNode poll = queue.poll();
if(poll.left!=null){
queue.add(poll.left);
}
if(poll.right!=null){
queue.add(poll.right);
}
list.add(poll.val);
}
if(isLeft){
result.add(list);
}else{
ArrayList<Integer> listR = new ArrayList<>(list.size());
for (int i = list.size() - 1; i >= 0; i--) {
listR.add(list.get(i));
}
result.add(listR);
}
isLeft = !isLeft;
}
return result;
}
}