LeetCode117—Populating Next Right Pointers in Each Node II
原题
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
Subscribe to see which companies asked this question
分析
参考LeetCode116—Populating Next Right Pointers in Each Node直接bfs层序遍历即可
代码
class Solution {
private:
void bfs(TreeLinkNode *root)
{
if (root == NULL)
return;
vector<TreeLinkNode*>temp;
vector<TreeLinkNode*>q;
int front = 0;
int rear = 1;
q.push_back(root);
while (front < q.size())
{
rear = q.size();
while (front < rear)
{
temp.push_back(q[front]);
if (q[front]->left != NULL)
q.push_back(q[front]->left);
if (q[front]->right != NULL)
q.push_back(q[front]->right);
++front;
}
int i;
for ( i = 0; i < temp.size()-1; i++)
{
temp[i]->next = temp[i + 1];
}
temp[i]->next = NULL;
temp.clear();//结束一层
}
}
public:
void connect(TreeLinkNode *root) {
bfs(root);
}
};