Skip to content

Instantly share code, notes, and snippets.

@mengdiwang
Created October 30, 2015 21:12
Show Gist options
  • Save mengdiwang/b2784376045180065f89 to your computer and use it in GitHub Desktop.
Save mengdiwang/b2784376045180065f89 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) {
//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