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
解题思想:
就是要找到每一个开始的节点,用BFS,把每一层走完。
递推思想 依然不需要改变,依然是依据当前层的next 指针,设置下一层的 next 指针。只是找结点麻烦些,我们定义了两个函数,findNextNodeNextLev用来找(n+1)层的下一个节点,findStartNodeNextLev来找这一层的第一个节点。通过调用,findNextNodeNextLev来找,找到了返回。
class Solution {
public:
void connect(TreeLinkNode *root)
{
if (NULL==root)
{
return;
}
TreeLinkNode *start;
TreeLinkNode *curNode;
TreeLinkNode *nextNode;
while (root!=NULL)
{
start = findStartNodeNextLev(root);
curNode=start;
nextNode=findNextNodeNextLev(root,start); //nextLev First,nexNode
while(nextNode!=NULL)
{
curNode->next=nextNode;
curNode=nextNode;
nextNode=findNextNodeNextLev(root,curNode);
}
root=start;
}
}
private:
TreeLinkNode* findNextNodeNextLev(TreeLinkNode* &cur,TreeLinkNode* curNextLev)
{
if(cur->left==curNextLev&&cur->right!=NULL)
{
return cur->right;
}
else
{
while(cur->next!=NULL)
{
cur=cur->next;
if(cur->left!=NULL&&cur->left!=curNextLev) return cur->left;
if(cur->right!=NULL&&cur->right!=curNextLev) return cur->right;
}
}
return NULL;
}
TreeLinkNode* findStartNodeNextLev(TreeLinkNode* node)
{
if(NULL == node) return NULL;
if(node->left!=NULL)return node->left;
return findNextNodeNextLev(node,node->left);
}
};