```
void connect(TreeLinkNode *p) {
while(p){
TreeLinkNode *nexth=NULL,*nextp=NULL;
while(p){
if(p->left){
nexth=nextp=p->left;
break;
}
if(p->right){
nexth=nextp=p->right;
break;
}
p=p->next;
}
while(p){
if(p->left)nextp=nextp->next=p->left;
if(p->right)nextp=nextp->next=p->right;
p=p->next;
}
p=nexth;
if(nextp)nextp->next=NULL;
}
}
```