/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
if(!root) return;
queue<TreeLinkNode*> t;
t.push(root);
while(!t.empty()){
int s = t.size();
TreeLinkNode* last = t.front(); t.pop();
if(last->left) t.push(last->left);
if(last->right) t.push(last->right);
for(int i=1;i<s;i++){
TreeLinkNode* tt = t.front(); t.pop();
if(tt->left) t.push(tt->left);
if(tt->right) t.push(tt->right);
last->next = tt;
last = tt;
}
last->next = NULL;
}
}
};