1、题目描述
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
2、思路
使用队列遍历每一层,然后每一层用NULL作为标志隔开每一层。
3、代码
方案1、根据2中的思路:
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) {
if (!root)
return;
queue<TreeLinkNode *> q;
q.push(root);
q.push(NULL); //每一层用一个NULL来判别
TreeLinkNode *cur, *next;
cur = q.front();
q.pop();
while (cur) {
if (cur->left)
q.push(cur->left);
if (cur->right)
q.push(cur->right);
next = q.front();
q.pop();
if (next) { //如果不为NULL,还未结束,则继续遍历这一层
cur->next = next;
cur = next;
}
else { //遇到NULL,表示遍历上一层结束
q.push(NULL); //上一层结束是,下一层进队列也结束
cur = q.front();
q.pop();
}
}
}
};
方案2、其它参考代码:
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)
{
while(root)
{
TreeLinkNode dummy(-1), *prev;
prev = &dummy;
for(auto p = root; p; p = p->next)
{
if(p->left)
{
prev->next = p->left;
prev = prev->next;
}
if(p->right)
{
prev->next = p->right;
prev = prev->next;
}
}
root = dummy.next; // 指向下一层的第一个节点
}
}
};