题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
/*
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) {
Queue<TreeNode> q = new LinkedList<>();
ArrayList<ArrayList<Integer>> list1 = new ArrayList<>();
if(pRoot == null){
return list1;
}
TreeNode node = pRoot;
q.offer(node);
int s = 0;
while(!q.isEmpty()){
int size = q.size();
ArrayList<Integer> list = new ArrayList<>();
for(int i = 0;i < size;i++){
TreeNode cur = q.poll();
if((s%2) == 0){
list.add(cur.val);
}else{
list.add(0,cur.val);
}
if(cur.left != null){
q.offer(cur.left);
}
if(cur.right != null){
q.offer(cur.right);
}
}
s++;
list1.add(list);
}
return list1;
}
}

查看23道真题和解析