struct TreeLinkNode {
int val;
TreeLinkNode *left, *right, *next;
TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
};
void connect(TreeLinkNode *root) {
TreeLinkNode *p = root;
TreeLinkNode *nextFirst = NULL;
TreeLinkNode *q = NULL;
while(p != NULL) {
if (p->left) {
if (q == NULL) {
nextFirst = p->left;
q = p->left;
} else {
q->next = p->left;
q = q->next;
}
}
if (p->right) {
if (nextFirst == NULL) {
nextFirst = p->right;
q = p->right;
} else {
q->next = p->right;
q = q->next;
}
}
p = p->next;
if (p == NULL) {
p = nextFirst;
nextFirst = NULL;
q = NULL;
}
}
}