my using Deque wonderful solution


  • 0
    C
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> ret = new ArrayList<List<Integer>>();
            if(root == null){
                return ret;
            }
            Deque<TreeNode> queue = new LinkedList<TreeNode>();
            boolean helper = true;
            queue.offer(root);
            while(!queue.isEmpty()){
                int curSize = queue.size();
                List<Integer> list = new ArrayList<Integer>();
                for(int i = 0;i<curSize;i++){
                    if(helper){
                        TreeNode tmp = queue.poll();
                        if(tmp.left!=null){
                            queue.offer(tmp.left);
                        }
                        if(tmp.right!=null){
                            queue.offer(tmp.right);
                        }
                        list.add(tmp.val);
                    }else{
                        TreeNode tmp = queue.pollLast();
                        if(tmp.right!=null){
                            queue.offerFirst(tmp.right);
                        }
                        if(tmp.left!=null){
                            queue.offerFirst(tmp.left);
                        }
                        list.add(tmp.val);
                    }
                    
                }
                helper = !helper;
               ret.add(list);
            }
            return ret;
        }
    }
    

Log in to reply
 

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