一个队列实现,分奇偶层,偶数层反转一下。
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) {
Queue<TreeNode> queue = new LinkedList<>();
TreeNode p1;
ArrayList<ArrayList<Integer> > re = new ArrayList<>();
ArrayList<Integer> list = new ArrayList<>();
queue.offer(pRoot);
int size;
int k=0;
if(pRoot == null){
return re;
}
while(!queue.isEmpty()){
size = queue.size();
k++;
while(size>0){
size--;
p1 = queue.poll();
list.add(p1.val);
if(p1.left != null ){
queue.offer(p1.left);
}
if(p1.right != null ){
queue.offer(p1.right);
}
}
if(list.size() != 0){
if(k % 2 ==0){
Collections.reverse(list);
re.add(new ArrayList(list));
}else{
re.add(new ArrayList(list));
}
}
list.clear();
}
return re;
}
}