```
void connect(TreeLinkNode *root) {
TreeLinkNode *pred = NULL, *beg = root, *cur = root;
while (beg) {
if (pred) {
if (pred->left == cur) {
pred->left->next = pred->right;
} else if (pred->next) {
pred->right->next = pred->next->left;
}
}
if (pred) {
if (pred->next==NULL) { // next level
pred = beg;
beg = beg->left;
cur = beg;
} else { // same level
if (pred->right == cur)
pred = pred->next;
cur = cur->next;
}
} else { // root
pred = beg;
beg = beg->left;
cur = beg;
}
}
}
```