My Easy AC Java Code


  • 0
    S

    The code is easy to understand.

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
            if (root == null) {
                return result;
        }
            
        Queue<TreeNode> queue = new LinkedList<>();
        int level = 0;
        queue.offer(root);
            
        while (!queue.isEmpty()) {
            int size = queue.size();
                
            LinkedList<Integer> list = new LinkedList<>();
          
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                if (level % 2 == 0) {
                    list.add(node.val);
                } else {
                    list.addFirst(node.val);
                }
            }
                
            level++;
            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.