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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
while(root)
{
TreeLinkNode* nextLevel = NULL;//first node in next level, eg. first child in current level
TreeLinkNode* prevChild = NULL;//previous node in child level, eg. link previous child's next to current child
for(; root; root = root->next)//current level
{
if(root->left)
{
if(!nextLevel)
nextLevel = root->left;
if(prevChild)
prevChild->next = root->left;
prevChild = root->left;
}
if(root->right)
{
if(!nextLevel)
nextLevel = root->right;
if(prevChild)
prevChild->next = root->right;
prevChild = root->right;
}
}//end of level traverse
root = nextLevel;
}
}
};
second time
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == NULL) return ;
root->next = NULL;
TreeLinkNode* prevHead = root;
while(prevHead != NULL)
{
TreeLinkNode* cur = prevHead;
TreeLinkNode* prev = NULL;
while(cur != NULL)
{
if(prev != NULL) prev->next = cur->left;//...
if(cur->left != NULL) cur->left->next = cur->right, prev = cur->right;//full tree
else break;//...
cur = cur->next;
}
if(prev != NULL) prev->next = NULL;
prevHead = prevHead->left;//...
}
}
};