题目描述:
给定一个二叉树
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL
。
初始状态下,所有 next 指针都被设置为 NULL
。
说明:
- 你只能使用额外常数空间。
- 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
示例:
给定二叉树,
1 / \ 2 3 / \ \ 4 5 7
调用你的函数后,该二叉树变为:
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
AC C++ Solution:
这是BFS遍历。现在指针是当前层的遍历,head是下一层的最左边元素,tail是下一层的最右边元素。将指针在当前层移动并填充其子层。(当前层遍历完毕移动到下一层的头部,这种关系已经在上一层遍历中填充填充)
class Solution {
public:
void connect(TreeLinkNode *root) {
TreeLinkNode *now, *tail, *head;
now = root;
head = tail = NULL;
while(now) {
if(now->left) {
if(tail)
tail = tail->next = now->left;
else
head = tail = now->left;
}
if(now->right) {
if(tail)
tail = tail->next = now->right;
else
head = tail = now->right;
}
if(!(now = now->next)) { //若now没有next,则将now设置为下一行头节点,开始遍历下一行节点
now = head;
head = tail = NULL;
}
}
}
};