请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
这题就是BFS,需要判断层数。反转可以用list.add(index, T): 将元素插入index位置或者Collection.reverse()或者用个额外list,奇偶层可以用位判断也可以用boolean也可以求余。
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > ans = new ArrayList<>();
if(pRoot == null) return ans;
Queue<TreeNode> q = new LinkedList<>();
q.add(pRoot);
int depth = 1;
ArrayList<Integer> dep = new ArrayList<>();
ArrayList<Integer> tmp = new ArrayList<>();
while(!q.isEmpty()){
int size = q.size();
for(int i = 0; i < size; i++){
TreeNode cur = q.poll();
if(depth%2 == 1){
dep.add(cur.val);
}else{
tmp.add(cur.val);
}
if(cur.left != null){
q.add(cur.left);
}
if(cur.right != null){
q.add(cur.right);
}
}
if(depth%2 == 0){
for(int i = tmp.size()-1; i >= 0; i--){
dep.add(tmp.get(i));
}
tmp.clear();
}
ans.add(new ArrayList<>(dep));
dep.clear();
depth++;
}
return ans;
}
}