my accepted solution by using queue


  • 0
    Y
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            Queue<TreeNode> queue=new LinkedList<TreeNode>();
            List<List<Integer>> res=new ArrayList<List<Integer>>();
            if(root==null) return res;
            queue.offer(root);
            int flag=1;
            while(!queue.isEmpty()){
                int size=queue.size();
                List<Integer> list=new ArrayList<>();
                for(int i=0;i<size;i++){
                    if(queue.peek().left!=null) queue.offer(queue.peek().left);
                    if(queue.peek().right!=null) queue.offer(queue.peek().right);
                    if(flag==1){
                         list.add(queue.poll().val);
                    }
                    else if(flag==-1){
                        list.add(0,queue.poll().val);
                    }
                }
                flag=flag*-1;
                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.