My ac java solution, but I met a problem.


  • 0
    T

    Here is my ac java solution. It just based on level order traverse method. But I have a question about my code. If n % 2 == 0, then I should add the queue.poll().val into the first position of the list. At the beginning, I used addFirst(), but there was compile error, it said cannot find method addFirst(), and used offerFirst() return the same result. In the end, I used add(0, queue.poll().val), it passed. I want to know the reason for this compile error. Welcome to comment and judge!

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new LinkedList<List<Integer>>();
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            if (root == null) return res;
            queue.offer(root);
            int n = 0;
            while (!queue.isEmpty()) {
                int level = queue.size();
                n++;
                List<Integer> list = new LinkedList<Integer>();
                for (int i = 0; i < level; i++) {
                    if (queue.peek().left != null) queue.offer(queue.peek().left);
                    if (queue.peek().right != null) queue.offer(queue.peek().right);
                    if (n % 2 == 0) {
                        // right -> left
                        list.add(0, queue.poll().val);
                    }
                    else {
                        // left -> right
                        list.add(queue.poll().val);
                    }
                    
                }
                res.add(list);
            }
            return res;
        }
    

Log in to reply
 

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