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思路:与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) {
TreeLinkNode *temp;
int flag=0;
if(root == NULL) return;
if(root->left != NULL){
temp=root;
flag=0;
while(temp!=NULL){
if(temp->left!=NULL && temp->left!=root->left){
root->left->next=temp->left;
flag=1;
break;
}
if(temp->right!=NULL){
root->left->next=temp->right;
flag=1;
break;
}
temp=temp->next;
}
if(flag==0) root->left->next=NULL;
}
if(root->right !=NULL){
flag=0;
temp=root->next;
while(temp!=NULL){
if(temp->left!=NULL){
root->right->next=temp->left;
flag=1;
break;
}
if(temp->right!=NULL){
root->right->next=temp->right;
flag=1;
break;
}
temp=temp->next;
}
if(flag==0) root->right->next=NULL;
}
connect(root->right);
connect(root->left);
}
};