Compared with I version, the tree could be incomplete. The only difference is that, we connect current node's child to next non-childrenless' node's first child.
Still, we need calculate from right to left:
class Solution { public: void connect(TreeLinkNode *p) { if (!p) return; if (p->right) { p->right->next = NULL; if (p->next) { TreeLinkNode *pTmp = p->next; while (pTmp) { if (pTmp->left || pTmp->right) break; pTmp = pTmp->next; } if (pTmp) { if (pTmp->left) p->right->next = pTmp->left; else if (pTmp->right) p->right->next = pTmp->right; } } } if (p->left) { if (p->right) p->left->next = p->right; else { TreeLinkNode *pTmp = p->next; while (pTmp) { if (pTmp->left || pTmp->right) break; pTmp = pTmp->next; } if (pTmp) { if (pTmp->left) p->left->next = pTmp->left; else if (pTmp->right) p->left->next = pTmp->right; } } } connect(p->right); connect(p->left); } };