1class Solution {2public Node connect(Node root) {3if (root == null) {4return root;5}6Node head = null; // the start node of next level, the first left of next level7Node prev = null; // the next pointer8Node curr = root;910while (curr != null) {11// traverse the whole current level, left -> right, until we meet a null pointer12while (curr != null) {13if (curr.left != null) {14if (head == null) {15head = curr.left;16prev = curr.left;17} else {18prev.next = curr.left;19prev = prev.next;20}21}2223if (curr.right != null) {24if (head == null) {25head = curr.right;26prev = curr.right;27} else {28prev.next = curr.right;29prev = prev.next;30}31}32curr = curr.next;33}3435curr = head;36prev = null;37head = null;38}39return root;40}41}