import java.util.ArrayList;
import java.util.LinkedList;

/*
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>> ans = new ArrayList<>();
        if(root == null) {
            return ans;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.addLast(root);
        boolean flag = true;
        while(queue.size() > 0) {
            ArrayList<Integer> lvl = new ArrayList<>();
            int sz = queue.size();
            if(flag) {
                for(int i = 0; i < sz; i++) {
                    TreeNode tmp = queue.removeFirst();
                    lvl.add(tmp.val);
                    if(tmp.left  != null) queue.addLast(tmp.left);
                    if(tmp.right != null) queue.addLast(tmp.right);
                }
            } else {
                for(int i = 0; i < sz; i++) {
                    TreeNode tmp = queue.removeLast();
                    lvl.add(tmp.val);
                    if(tmp.right != null) queue.addFirst(tmp.right);
                    if(tmp.left  != null) queue.addFirst(tmp.left);
                }
            }
            ans.add(lvl);
            flag = !flag;
        }
        return ans;
    }

}