/**
* 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;
// TreeLinkNode* tmp = root->next;
// // 找到下一个节点
// while(tmp){
// if (tmp->left){
// tmp = tmp->left;
// break;
// }
// if (tmp->right){
// tmp = tmp->right;
// break;
// }
// tmp = tmp->next;
// }
// // 注意先右后左,先把右边的串起来,再串左边
// if (root->right) root->right->next = tmp;
// if (root->left) root->left->next = root->right ? root->right : tmp;
// connect(root->right);
// connect(root->left);
// }
// };
class Solution {
public:
void connect(TreeLinkNode *root) {
TreeLinkNode *start = new TreeLinkNode(0), *t = start;
while(root){
// 用start开头的链表将这一层串起来
if (root->left) {
t->next = root->left;
t = t->next;
}
if (root->right){
t->next = root->right;
t = t->next;
}
root = root->next;
// 到达这层的尽头了,进入下一层
if (!root){
root = start->next;
start->next = NULL;
t = start;
}
}
}
};
static int x=[](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();