public ArrayList<ArrayList<Integer>> zigzagLevelOrder (TreeNode root) {
        // write code here
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if (root==null) return res;
        Queue<TreeNode> queue=new LinkedList<>();
        queue.add(root);
        ArrayList<Integer> list = new ArrayList<>();
        int flag=0;
        while (queue.size()>0){
            int len = queue.size();
            list= new ArrayList<>();
            for (int i=1;i<=len;i++){
                TreeNode temp = queue.poll();
                list.add(temp.val);
                if (temp.left!=null){
                    queue.add(temp.left);
                    //System.out.println(temp.left.val);
                }
                if(temp.right!=null) {
                    queue.add(temp.right);
                    //System.out.println(temp.right.val);
                }
            }
            if (flag%2==1)
                Collections.reverse(list);
            flag++;
            res.add(list);
        }
        return res;
    }