I:
连相同列,再遍历下一层的相同列
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (!root) return;
if (root->left) {
TreeLinkNode *l=root->left, *r=root->right;
while (l) {
l->next=r;
l=l->right;
r=r->left;
}
connect(root->left);
connect(root->right);
}
}
};
II:
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
TreeLinkNode *cur = root;
while (cur) {
TreeLinkNode *pre=NULL, *next=NULL;
for ( ; cur!=NULL; cur=cur->next) {
if (!next) next=cur->left?cur->left:cur->right;
if (cur->left) {
if (pre) pre->next=cur->left;
pre=cur->left;
}
if (cur->right) {
if (pre) pre->next=cur->right;
pre=cur->right;
}
}
cur=next;
}
}
};