Skip to content

Instantly share code, notes, and snippets.

@chuchao333
Created November 22, 2014 08:58
Show Gist options
  • Save chuchao333/4ea622293912e893b6f6 to your computer and use it in GitHub Desktop.
Save chuchao333/4ea622293912e893b6f6 to your computer and use it in GitHub Desktop.
Populating Next Right Pointers in Each Node
/**
* 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