Using Deque - My accepted java Solution


  • 1
    R
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            if(root == null) return new LinkedList<List<Integer>>();
            List<List<Integer>> mylist = new LinkedList<List<Integer>>();
            Deque<TreeNode> myqueue = new LinkedList<TreeNode>();
            
            int zigzag=1;
            myqueue.offer(root);
            while(!myqueue.isEmpty()){
                List<Integer> sublist = new LinkedList<Integer>();
                int level = myqueue.size();
                for(int i=0;i<level;i++){
                    if(zigzag%2==0){
                        if(myqueue.peek().right!=null) myqueue.offer(myqueue.peek().right);
                          if(myqueue.peek().left!=null) myqueue.offer(myqueue.peek().left);
                          sublist.add(myqueue.poll().val);
                    }
                    else{
                        if(myqueue.peekLast().left!=null) myqueue.addFirst(myqueue.peekLast().left);
                        if(myqueue.peekLast().right!=null) myqueue.addFirst(myqueue.peekLast().right);
                        sublist.add(myqueue.pollLast().val);
                    }
                  
                }
                 mylist.add(sublist); 
              zigzag++;  
            }
            
            return mylist;
        }
    }
    

Log in to reply
 

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