请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
public class Solution {
ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
if (pRoot == null) {
return lists;
}
int time = 1;
Stack<TreeNode> s1 = new Stack<>();
s1.push(pRoot);
Stack<TreeNode> s2 = new Stack<>();
while (!s1.isEmpty() || !s2.isEmpty()) {
ArrayList<Integer> temp = new ArrayList<>();
if (time % 2 != 0){
while (!s1.isEmpty()){
TreeNode p = s1.pop();
if(p != null){
temp.add(p.val);
s2.push(p.left);
s2.push(p.right);
}
}
}else{
while (!s2.isEmpty()){
TreeNode p = s2.pop();
if(p != null){
temp.add(p.val);
s1.push(p.right);
s1.push(p.left);
}
}
}
if(temp.size() != 0){
lists.add(temp);
time++;
}
}
return lists;
}
}