```
class Solution {
private:
TreeLinkNode *getNext(TreeLinkNode *node) {
while (node) {
if (node->left) {
return node->left;
}
if (node->right) {
return node->right;
}
node = node->next;
}
return nullptr;
}
public:
void connect(TreeLinkNode *root) {
if (!root) {
return;
}
if (root->left) {
root->left->next = root->right ?: getNext(root->next);
}
if (root->right) {
root->right->next = getNext(root->next);
}
connect(root->right);
connect(root->left);
}
};
```