straightforward but O(N) space

class Solution {
public:
void connect(TreeLinkNode *root) {
if(!root) return;
queue<TreeLinkNode*> inqueue,out;
out.push(root);
queue<TreeLinkNode*>& outqueue = out;
while(!outqueue.empty())
{
TreeLinkNode* tem = outqueue.front();
outqueue.pop();
if(!outqueue.empty()) tem->next = outqueue.front();
if(tem->left) inqueue.push(tem->left);
if(tem->right) inqueue.push(tem->right);
if(outqueue.empty())
{
outqueue = inqueue;inqueue = queue<TreeLinkNode*>();
}
}
}
};