educative.io

Educative

Why not use peek to point to the next element?

Something like this:
while(!queue.isEmpty()){
int size = queue.size();
level++;
for(int i = 0; i<size; i++) {
TreeNode pop = queue.poll();
if(pop.left !=null)
queue.offer(pop.left);
if(pop.right !=null)
queue.offer(pop.right);
if (i == size-1) {
pop.next = null;
} else {
pop.next = queue.peek();
}
}