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 = &nextFirst;
while(p != NULL) {
if (p->left) {
*q = p->left;
q = &(p->left->next);
}
if (p->right) {
*q = p->right;
q = &(p->right->next);
}
p = p->next;
if (p == NULL) {
p = nextFirst;
nextFirst = NULL;
q = &nextFirst;
}
}
}