One queue and one while loop, best iterative in java????


  • 0
    C
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            if(root == null) return res;
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.offer(root);
            int count = 1;
            boolean leftToRight = true;
            List<Integer> list = new ArrayList<Integer>();
            while(!queue.isEmpty()){
                TreeNode node = queue.poll();
                if(leftToRight){
                    list.add(node.val);
                } else {
                    list.add(0, node.val);
                }
                if(node.left != null) queue.offer(node.left);
                if(node.right != null) queue.offer(node.right);
                if(--count == 0){
                    res.add(new ArrayList<Integer>(list));
                    count = queue.size();
                    list.clear();
                    leftToRight = !leftToRight;
                }
            }
            return res;
        }
    }

Log in to reply
 

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