public Node connect(Node root){ if (root==null){ returnnull; } LinkedList<Node> queue = new LinkedList<>(); queue.addLast(root); while (!queue.isEmpty()) { int length = queue.size();
for (int i = 0; i < length; i++) { Node temp = queue.poll();
if (temp.left != null) { queue.add(temp.left); } if (temp.right != null) { queue.add(temp.right); }
if (i == length - 1) { temp.next = null; } else { temp.next = queue.element(); }