public void connect(TreeLinkNode root) {
if (root == null) {
return;
}
TreeLinkNode first = null;// first in next level
TreeLinkNode pointer = null;// pointer to go right
TreeLinkNode cur = root;// current level
while (cur != null) {
while (cur != null) {
// if have left
if (cur.left != null) {
// and we are not at the 1st
if (pointer != null) {
pointer.next = cur.left;
} else {
first = cur.left;
}
pointer = cur.left;
}
if (cur.right != null) {
if (pointer != null) {
pointer.next = cur.right;
} else {
first = cur.right;
}
pointer = cur.right;
}
cur = cur.next;
}
cur = first;
first = null;
pointer = null;
}
}