import java.util.*;

/*
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 root) {
         ArrayList<ArrayList<Integer>> list = new ArrayList<>();
         if(root == null) return list;
         Deque<TreeNode> stack = new LinkedList<>();
         Queue<TreeNode> queue = new LinkedList<>();
         queue.offer(root);
         boolean change = false;
         while(!queue.isEmpty()){
             int size = queue.size();
             ArrayList<Integer> child = new ArrayList<>();
             if(change){
                  while(size -- != 0){
                      TreeNode node = queue.poll();
                      child.add(node.val);
                      if(node.right != null) stack.push(node.right);
                      if(node.left != null) stack.push(node.left);
                  }
             }else {
                  while(size -- != 0){
                       TreeNode node = queue.poll();
                       child.add(node.val);
                      if(node.left != null) stack.push(node.left);
                      if(node.right != null) stack.push(node.right);
                  }
             }
             change = !change;
             list.add(child);
             while(!stack.isEmpty()){
                 queue.offer(stack.pop());
             }
             
         }
        return list;
    }
}