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
指出每个节点的下一个右侧节点,前一篇博客的那个思路也可以继续使用,但由于这里的二叉树是任意的,所以应该用函数找到下一层的开始节点以及下一层的下一个节点,代码如下:
class Solution{
public:
void connect(TreeLinkNode *root)
{
TreeLinkNode * prev, * curr, * start;
if(!root) return;
while(root){
start = findNextLevelStartNode(root);
prev = start;
curr = findNextLevelNextNode(root, prev);
while(curr){
prev->next = curr;
prev = curr;
curr = findNextLevelNextNode(root, curr);
}
root = start;
}
}
private:
TreeLinkNode * findNextLevelNextNode(TreeLinkNode * & node, TreeLinkNode * curr)//注意使用引用
{
if(node->left == curr && node->right)
return node->right;
else{
while(node->next){
node = node->next;
if(node->left != NULL && node->left != curr) return node->left;
if(node->right != NULL && node->right != curr) return node->right;
}
}
return NULL;
} TreeLinkNode * findNextLevelStartNode(TreeLinkNode * node)
{
if(!node) return NULL;
if(node->left)
return node->left;
else return findNextLevelNextNode(node, node->left);
}
};