Use deque to solve


  • 0
    H

    It is better to use Deque, since list to insert (0, value) will cost all the existing element in list to move right by 1 place.
    I have been questioned about this in my interview, so it is better to avoid doing insert(0, value) or add(0, value) in arrayList.

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List resl = new ArrayList();
            if(root == null) return resl;
            Deque<TreeNode> currentLayer = new LinkedList<>();
            currentLayer.offer(root);
            boolean rightToLeft = false;
            while(!currentLayer.isEmpty()){
                List<Integer> solution = new ArrayList<Integer>();
                int n = currentLayer.size();
                for(int i = 0; i<n; i++){
                    TreeNode node = null;
                    if (rightToLeft) {
                        node = currentLayer.pollLast();
                        if (node.right!=null) {
                            currentLayer.offerFirst(node.right);
                        }
                        if (node.left != null) {
                            currentLayer.offerFirst(node.left);
                        }
                    }
                    else {
                        node = currentLayer.pollFirst();
                        if(node.left!=null){
                            currentLayer.offer(node.left);
                        }
                        if(node.right!=null){
                            currentLayer.offer(node.right);
                        }
                    }
                    solution.add(node.val);
                }
                resl.add(solution);
                rightToLeft = !rightToLeft;
            }
            return resl; 
        }
    

Log in to reply
 

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