题目:
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
代码如下:
void build(TreeLinkNode *root)
{
if(root->left!=NULL)
{
if(root->right!=NULL)
root->left->next=root->right;
else
{
if(root->next!=NULL)
{
TreeLinkNode *tmp=root;
while(tmp->next!=NULL)
{
if(tmp->next->left!=NULL)
{
root->left->next=tmp->next->left;
break;
}
else if(tmp->next->right!=NULL)
{
root->left->next=tmp->next->right;
break;
}
else
{
tmp=tmp->next;
}
}
if(tmp->next==NULL)
{
root->left->next=NULL;
}
}
else
{
root->left->next=NULL;
}
}
build(root->left);
}
if(root->right!=NULL)
{
TreeLinkNode *tmp=root;
if(tmp->next!=NULL)
{
while(tmp->next!=NULL)
{
if(tmp->next->left!=NULL)
{
root->right->next=tmp->next->left;
break;
}
else if(tmp->next->right!=NULL)
{
root->right->next=tmp->next->right;
break;
}
else
tmp=tmp->next;
}
if(tmp->next==NULL)
{
root->right->next=NULL;
}
}
else
{
root->right->next=NULL;
}
build(root->right);
}
}
void connect(TreeLinkNode *root) {
if(root==NULL)return;
root->next=NULL;
build(root);
return;
}