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