Java Simple Queue Method


  • 0
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<>();
            if (root == null){
                return result;
            }
            
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            boolean forward = true;
            
            while (queue.size() > 0){
                int size = queue.size();
                List<Integer> level = new ArrayList<>();
                for (int i = 0; i < size; i++){
                    TreeNode node = queue.poll();
                    level.add(node.val);
                    
                    if (node.left != null){
                        queue.add(node.left);
                    }
                    if (node.right != null){
                        queue.add(node.right);
                    }
                }
                if (!forward){
                    Collections.reverse(level);
                }
                result.add(level);
                forward = !forward;
            }
            return result;
        }
    }
    

Log in to reply
 

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