2ms iterative solution using deque


  • 0
    I
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            if(root == null){
                return new ArrayList<>();
            }
            List<List<Integer>> result = new ArrayList<>();
            Deque<TreeNode> deque = new LinkedList<>();
            deque.addFirst(root);
            boolean zigZag = false;
            while(!deque.isEmpty()){
                int size = deque.size();
                List<Integer> list = new ArrayList<>(size);
                for(int i = 0; i < size; i++){
                    if(zigZag){
                        TreeNode node = deque.pollLast();
                        list.add(node.val);
                        if(node.right != null){
                            deque.addFirst(node.right);
                        }
                        if(node.left != null){
                            deque.addFirst(node.left);
                        }
                    }
                    else {
                        TreeNode node = deque.removeFirst();
                        list.add(node.val);
                        if(node.left != null){
                            deque.offerLast(node.left);
                        }
                        if(node.right != null){
                            deque.offerLast(node.right);
                        }
                    }
                }
                zigZag = !zigZag;
                result.add(list);
            }
            return result;
        }
    }

Log in to reply
 

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