Created
October 12, 2017 05:00
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
auto curr = root; | |
while(curr) | |
{ | |
curr = findNext(curr); | |
if(!curr)break; | |
TreeLinkNode* head = curr->left? curr->left: curr->right; | |
while(curr) | |
{ | |
if(curr->left && curr->right) | |
curr->left->next = curr->right; | |
TreeLinkNode* next = findNext(curr->next); | |
if(!next)break; | |
if(curr->right)curr->right->next = next->left? next->left: next->right; | |
else curr->left->next = next->left? next->left: next->right; | |
curr = next; | |
} | |
curr = head; | |
} | |
} | |
private: | |
TreeLinkNode* findNext(TreeLinkNode* curr) | |
{ | |
while(curr) | |
{ | |
if(curr->left || curr->right) | |
return curr; | |
curr = curr->next; | |
} | |
return curr; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment