My accepted JAVA solution, one queue and without reverse operation.


  • 0
    A

    class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    List<List<Integer>> res = new LinkedList<>();
    if (null == root) {
    return res;
    }

        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        boolean oddFlag = true;
        while(!queue.isEmpty()){
            int levelNum = queue.size();
            List<Integer> list = new LinkedList<Integer>();
            for (int i = 0; i < levelNum; i++) {
                if(queue.peek().left != null) {
                    queue.offer(queue.peek().left);
                }
                if(queue.peek().right != null) {
                    queue.offer(queue.peek().right);
                }
                if(oddFlag) {
                    list.add(queue.poll().val);
                } else {
                    list.add(0, queue.poll().val);
                }
            }
            res.add(list);
            oddFlag = !oddFlag;
        }
        return res;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.