```
class Solution {
public:
void connect(TreeLinkNode *root){
queue<TreeLinkNode *> Q;
if (root)
Q.push(root);
// counters of nodes in current level and next level
int cur_cnt = 1, next_cnt = 0;
while (!Q.empty()) {
TreeLinkNode *node = Q.front(); Q.pop();
if (!node->left && !node->right) {
Q.push(node->left);
Q.push(node->right);
next_cnt += 2;
}
// last node in current level
if (!(--cur_cnt)) {
cur_cnt = next_cnt;
next_cnt = 0;
continue;
}
node->next = Q.front();
}
}
};
```