题目
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,同时连接下一层的非空节点。
由于下一层的点已经连接,只需要保存下一层的开始位置,不需要额外的队列记录,所以空间开销为O(1);
代码:
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
TreeLinkNode *pos,*next_level=root,*next_head=root; //当前处理位置,下一层处理到位置,下一层头
while(next_head!=NULL) //层序遍历
{
pos=next_head;
next_head=NULL;
next_level=NULL;
while(pos!=NULL) //搜索下一层
{
if(pos->left!=NULL) //处理左节点
{
if(next_head==NULL)
{
next_head=pos->left;
next_level=next_head;
}
else
{
next_level->next=pos->left;
next_level=next_level->next;
}
}
if(pos->right!=NULL) //处理右节点
{
if(next_head==NULL)
{
next_head=pos->right;
next_level=next_head;
}
else
{
next_level->next=pos->right;
next_level=next_level->next;
}
}
pos=pos->next;
}
}
}
};
本文探讨了如何通过宽度优先搜索(BFS)算法解决复杂二叉树中节点连接的问题,即使存在空节点。通过在不使用额外空间的情况下,仅保存下一层的开始位置,实现对树的层次遍历和节点链接,优化了空间复杂度。详细介绍了算法步骤和代码实现,包括处理左节点、右节点以及更新节点指针的逻辑。
2921

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



