```
class Solution {
public:
void connect(TreeLinkNode *root) {
if (!root) return;
queue<TreeLinkNode*> q, p;
p.push(root);
while (!p.empty()){
q = p;
queue<TreeLinkNode*> empty;
swap(p, empty);
TreeLinkNode *t = q.front();
t->next = NULL;
while (!q.empty()){
t = q.front();
q.pop();
if (t->right) p.push(t->right);
if (t->left) p.push(t->left);
if (!q.empty()) q.front()->next = t;
}
}
}
};
```