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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (root == NULL) {
return;
}
TreeLinkNode *next = root->next;
while (next != NULL && next->left == NULL && next->right == NULL) {
next = next->next;
}
if (next) {
if (next->left) {
next = next->left;
} else {
next = next->right;
}
}
if (root->left) {
if (root->left->next != NULL) {
return;
}
if (root->right) {
root->left->next = root->right;
} else {
root->left->next = next;
}
}
if (root->right) {
if (root->right->next != NULL) {
return;
}
root->right->next = next;
}
connect(root->next);
connect(root->left);
connect(root->right);
}
};