Populating Next Right Pointers in Each Node II
Oct 28 '12
423 / 1042
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
- You may only use constant extra space.
For example,
Given the following binary tree,
1 / \ 2 3 / \ \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
/**
* 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 == NULL) return;
root->next = NULL;
TreeLinkNode* par = root;
int left = 0;
TreeLinkNode* cur = get_next_child(par, left);
while (cur !=NULL) {
TreeLinkNode* head = cur;
while (cur != NULL) {
cur->next = get_next_child(par, left);
cur = cur->next;
}
par = head;left = 0;
cur = get_next_child(par, left);
}
}
TreeLinkNode* get_next_child(TreeLinkNode* & par, int& left) {
if (left == 2) par = par->next;
if (left == 1)
if (par->right != NULL) {left = 2; return par->right; }
else par = par->next;
while (par != NULL) {
if (par->left != NULL) { left=1; return par->left;}
if (par->right != NULL){ left=2; return par->right;}
par = par->next;
}
return NULL;
}
};