AC Java BFS solution


  • 0
    W
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            if (root == null) return res;
            
            Queue<TreeNode> q1 = new LinkedList<>();
            Queue<TreeNode> q2 = new LinkedList<>();
            
            boolean reverse = false;
            q1.offer(root);
            while (!q1.isEmpty()) {
                List<Integer> list = new LinkedList<>();
                for (TreeNode n : q1) {
                    if (reverse) {
                        list.add(0, n.val);
                    } else {
                        list.add(n.val);
                    }
                }
                reverse ^= true;
                res.add(list);
                while (!q1.isEmpty()) {
                    TreeNode curr = q1.poll();
                    if (curr.left != null) q2.offer(curr.left);
                    if (curr.right != null) q2.offer(curr.right);
                }
                Queue<TreeNode> tmp = q1;
                q1 = q2;
                q2 = tmp;
            }
            
            return res;
        }
    

Log in to reply
 

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