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
class Solution {
public:
void connect(TreeLinkNode *root) {
//NULL or has no children, nothing to do.
if(root == NULL || root->left == NULL && root->right == NULL)
return;
TreeLinkNode *p = root;
while(p != NULL)
{
TreeLinkNode *p_child = p->right ? p->right : p->left;
if(p->left && p->right)
p->left->next = p->right;
TreeLinkNode *p_next = p->next;
while(p_next && p_next->left == NULL && p_next->right == NULL)
p_next = p_next->next;
if(p_next && p_child)
p_child->next = p_next->left ? p_next->left : p_next->right;
p = p_next;
}
connect(root->left);
connect(root->right);
}
};