题目:
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 order(BinTree* root)
{
BinTree* temp = root;
BinTree* next_head = NULL;
if(temp == NULL)
return;
while(temp != NULL)
{
cout<<temp->value<<endl;
temp = temp->next;
}
temp = root;
while(temp != NULL)
{
if(temp->left != NULL)
{
next_head= temp->left;
break;
}
if(temp->right !=NULL)
{
next_head = temp->right;
break;
}
temp = temp->next;
}
order(next_head);
}
// pre_head 一直都是上一层的第一个节点
void helper_third(BinTree* pre_head)
{
BinTree* pre = pre_head;
BinTree* cur_first=NULL;
BinTree* cur_second=NULL;
BinTree* next_head=NULL;
while(pre != NULL && (cur_first == NULL || cur_second == NULL))
{
if(pre->left != NULL)
{
if(cur_first == NULL)
{
cur_first= pre->left;
next_head = cur_first;
}
else if(cur_second ==NULL)
cur_second = pre->left;
}
if(pre->right != NULL)
{
if(cur_first == NULL)
{
cur_first = pre->right;
next_head = cur_first;
}
else if(cur_second == NULL)
cur_second = pre->right;
}
if(cur_first != NULL && cur_second != NULL)
break;
pre = pre->next;
}
if(cur_first == NULL && cur_second == NULL)
return ;
while(pre != NULL)
{
cur_first->next = cur_second;
cur_first = cur_second;
if(cur_second == pre->left && pre->right != NULL)
{
cur_second = pre->right;
continue;
}
pre = pre->next;
while(pre != NULL)
{
if(pre->left != NULL)
{
cur_second = pre->left;
break;
}
if(pre->right != NULL)
{
cur_second = pre->right;
break;
}
pre = pre->next;
}
}
if(cur_first != NULL)
cur_first->next = NULL;
helper_third(next_head);
}
void Connect_third(BinTree* root)
{
if(root==NULL)
return ;
root->next = NULL;
helper_third(root);
}
ps:这道题的麻烦之处在于查找,需要逐步索引查找。