I solve the problem https://www.hackerrank.com/challenges/swap-nodes-algo exchange of trees under the specified tree at a certain level. If you specify a level at which you want to exchange sub-trees, equal to 4. Then, when a queue is non-empty, the poll () method does not return an object from the queue.
Here is the code:

class Node { int data; Node left; Node right; Node(int data) { this.data = data; this.left = null; this.right = null; } } public class Solution { public static void swapNode(Node root, int K) { int depth = 1; Queue<Node> level = new LinkedList<>(); if (depth == K) { Node temp = root.left; root.left = root.right; root.right = temp; } else { Queue<Node> qu = new LinkedList<>(); qu.offer(root); while (depth < K) { while (!qu.isEmpty()) { Node curr = null; curr = qu.poll(); level.add(curr.left); level.add(curr.right); } while (!level.isEmpty()) { qu.offer(level.remove()); } K--; } while (!qu.isEmpty()) { Node temp = null; Node n = qu.poll(); temp = n.left; n.left = n.right; n.right = temp; } } } public static void inorder_print(Node root) { if (root != null) { inorder_print(root.left); System.out.print(root.data + " "); inorder_print(root.right); } } public static void printNode(Node root, int K) { inorder_print(root); System.out.println(); } public static void main(String[] args) { Node root = new Node(1); Queue<Node> list = new LinkedList<>(); list.add(root); Scanner sc = new Scanner(System.in); int N = sc.nextInt(); Node curr; while (N-- > 0) { curr = list.poll(); int leftData = sc.nextInt(); int rightData = sc.nextInt(); curr.left = (leftData == -1) ? null : new Node(leftData); curr.right = (rightData == -1) ? null : new Node(rightData); if (curr.left != null) list.add(curr.left); if (curr.right != null) list.add(curr.right); } int T = sc.nextInt(); while (T-- > 0) { int K = sc.nextInt(); swapNode(root, K); printNode(root, K); } } } 

    1 answer 1

    Thanks to all. It was necessary to:

     while (!qu.isEmpty()) { Node curr = null; curr = qu.poll(); if (curr.left != null)level.add(curr.left); else level.add(new Node(-1)); if (curr.right != null) level.add(curr.right); else level.add(new Node(-1)); } 

    There was a null object in the queue. A NullPointerException occurred on it.