Created
November 22, 2014 08:58
-
-
Save chuchao333/4ea622293912e893b6f6 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) { | |
auto p = root; | |
// Loop invariant: p is always the 'left most' node at the current level | |
while (p != NULL) { | |
// q is used to walk through from left to right at the current level | |
auto q = p; | |
while (q != NULL) { | |
if (q -> left != NULL) | |
q -> left -> next = q -> right; | |
if (q -> next != NULL && q -> right != NULL) | |
q -> right -> next = q -> next -> left; | |
q = q -> next; | |
} | |
p = p -> left; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment