```
public void connect(TreeLinkNode root) {
if (root == null) return;
TreeLinkNode node = null, nextNode = null;
TreeLinkNode leftMost = null;
while (root != null) {
while (root != null) {
if (root.left != null) {
if (leftMost == null) leftMost = root.left;
if (node == null)
node = root.left;
else {
nextNode = root.left;
node.next = nextNode;
node = nextNode;
}
}
if (root.right != null) {
if (leftMost == null) leftMost = root.right;
if (node == null)
node = root.right;
else {
nextNode = root.right;
node.next = nextNode;
node = nextNode;
}
}
root = root.next;
}
root = leftMost;
leftMost = null;
node = null;
}
}
```