题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
本题依旧是一道广度优先遍历,与层次遍历写法并无太大差别,只需要在最后判断一下,level是否能够被2整除,不可以的话反转数组即可。
import java.util.ArrayList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > res = new ArrayList<>();
LinkedList<TreeNode> list = new LinkedList<>();
if(pRoot==null){
return res;
}
list.add(pRoot);
int level = 0;
while(!list.isEmpty()){
int curSize = list.size();
ArrayList<Integer> temp = new ArrayList<>();
while(curSize>0){
TreeNode node = list.poll();
if(node!=null){
temp.add(node.val);
if(node.left!=null){
list.add(node.left);
}
if(node.right!=null){
list.add(node.right);
}
}
curSize--;
}
if(level%2!=0){
Collections.reverse(temp);
}
res.add(temp);
level++;
}
return res;
}
}