Created
October 30, 2015 21:12
-
-
Save mengdiwang/b2784376045180065f89 to your computer and use it in GitHub Desktop.
Populating Next Right Pointers in Each Node
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) { | |
//assigning the pointer level by level, and queue is not needed because the next pointer works the same as queue | |
if(root == NULL) | |
return; | |
root->next = NULL; | |
TreeLinkNode *seed = root; | |
while(seed->left != NULL) | |
{ | |
TreeLinkNode *line = seed; | |
//assign children's next pointer | |
while(line->next) | |
{ | |
line->left->next = line->right; | |
line->right->next = line->next->left; | |
line = line->next; | |
} | |
//tail | |
line->left->next = line->right; | |
line->next = NULL; | |
line->right->next = NULL; | |
//iterate to the next | |
seed = seed->left; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment