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
answer:
class Solution {
public:
void connect(TreeLinkNode *root) {
TreeLinkNode temp(0);
TreeLinkNode * index = &temp;
TreeLinkNode * pre = root, * end = root, * end2 = root;
if(!root) return;
index->next = root;
while(index != end){
index = index->next;
pre->next = NULL;
if(index == NULL)
return;
if(index->left != NULL){
end2->next = index->left;
end2 = end2->next;
}
if(index->right != NULL){
end2->next = index->right;
end2 = end2->next;
}
if(index == end){
pre = end;
end = end2;
}
}
}
};
针对Populating Next Right Pointers in Each Node问题的进阶版本,本文介绍了一种仅使用常数额外空间填充任意二叉树节点的方法。通过一次遍历即可完成所有节点的填充工作,最终使得每个节点指向其右侧相邻的节点。

121

被折叠的 条评论
为什么被折叠?



