level order and list head/tail insertion


  • 0
    S
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<>();
            if (root == null) return result;
            
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            
            boolean leftToRight = true;
            
            while (!queue.isEmpty()) {
                int size = queue.size();
                List<Integer> list = new ArrayList<>();
                
                for (int i = 0; i < size; i++) {
                    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);
                    }
                }
                leftToRight = !leftToRight;
                result.add(list);
            }
            
            return result;
        }
    

Log in to reply
 

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