Java 2ms iterative solution


  • 0
    A
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> ans = new ArrayList<>();
            if (root==null) return ans;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            int dir=1;
            while (!queue.isEmpty()) {
                int size = queue.size();
                List<Integer> curr = new ArrayList<>();
                for (int i=0; i<size; i++) {
                    TreeNode node = queue.poll();
                    if (dir==1)
                        curr.add(node.val);
                    else
                        curr.add(curr.size()-i, node.val);
                    if (node.left != null)
                        queue.add(node.left);
                    if (node.right != null)
                        queue.add(node.right);
                }
                dir = 1-dir;
                ans.add(curr);
            }
            return ans;
        }
    }

Log in to reply
 

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