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
题目如上所示,这题实在I上进行的追问,第一题提交的太快,导致这道题大意了,原来想用递归的方法求解,但是没有清楚解的扩展方向,闲话不说直接上图:
代码如下:
class Solution {
public:
void connect(TreeLinkNode *root) {
TreeLinkNode *pLeftMost=root;
while (pLeftMost!=NULL){
TreeLinkNode *ptemp=pLeftMost;
while (ptemp!=NULL){
connectToNext(ptemp);
ptemp=ptemp->next;
}
pLeftMost= findLeftMost(pLeftMost);
}
pLeftMost = root;
while (pLeftMost!=NULL){
TreeLinkNode *tep=pLeftMost;
while (tep!=NULL)
{
cout<<tep->val<<" ";
tep=tep->next;
}
cout<<"# ";
pLeftMost= findLeftMost(pLeftMost);
}
}
TreeLinkNode *findLeftMost(TreeLinkNode *preLeftMost){
while (preLeftMost!=NULL){
if(preLeftMost->left!=NULL)
{
return preLeftMost->left;
}
if (preLeftMost->right!=NULL)
{
return preLeftMost->right;
}
preLeftMost=preLeftMost->next;
}
return NULL;
}
void connectToNext(TreeLinkNode *root){
if (root==NULL)
{
return;
}
TreeLinkNode *pSet=root->left;
TreeLinkNode *pSetNext=NULL;
//左儿子节点不空
if (pSet!=NULL){
//如果当前节点的左右儿子都不空,则设左儿子的next节点为右儿子
//同时更改需要设置next的节点为当前节点的右儿子
if(root->right!=NULL){
pSet->next=root->right;
pSet=root->right;
}
}
else{
//左儿子节点为空,设需要更改next域的节点为右儿子
pSet=root->right;
}
//当前节点的左右儿子都为空
if (pSet==NULL)
{
/*connectToNext(root->next);*/
return;
}
//find pSet's next
TreeLinkNode *ptemp=root->next;
while (ptemp!=NULL){
if (ptemp->left!=NULL){
pSetNext=ptemp->left;
break;
}
if (ptemp->right!=NULL){
pSetNext=ptemp->right;
break;
}
ptemp=ptemp->next;
}
pSet->next=pSetNext;
/* connectToNext(root->next);*/
}
};