My Java solution in 3ms


  • 0
    I
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List result = new ArrayList();
            if(root == null){
                return result;
            }
            Queue<TreeNode> queue = new LinkedList<TreeNode>();//queue is implemented by linkedlist
            queue.offer(root);
            int timer = 0;
            while(!queue.isEmpty()){
                ArrayList<Integer> level = new ArrayList<Integer>();
                int size = queue.size();
                for(int i = 0; i < size; i++){
                    TreeNode node = queue.poll();
                    level.add(node.val);
                    if(node.left != null){
                        queue.offer(node.left);
                    }
                    if(node.right != null){
                        queue.offer(node.right);
                    }
                }
                timer++;
                if(timer%2 == 0){
                    Collections.reverse(level);
                }
                result.add(level);
            }
            return result;
        }
    

Log in to reply
 

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