题目
Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
After calling your function, the tree should look like:
分析
为满二叉树添加线索;
由题目可知,线索是根据层序链接,每一层终止节点线索为空,其余节点的next为其层序的下一个节点;
利用层序遍历解决该问题;类似于 LeetCode(102) Binary Tree Level Order Traversal。
AC代码
/**
* 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) {
if (!root)
return;
//定义两个队列,一个存储父节点
queue<TreeLinkNode *> parent;
parent.push(root);
root->next = NULL;
while (!parent.empty())
{
//定义队列存储当前子层
queue<TreeLinkNode*> curLevel;
while (!parent.empty())
{
TreeLinkNode *tmp = parent.front();
parent.pop();
if (tmp->left)
curLevel.push(tmp->left);
if (tmp->right)
curLevel.push(tmp->right);
}//while
parent = curLevel;
while (!curLevel.empty())
{
TreeLinkNode *p = curLevel.front();
curLevel.pop();
if (!curLevel.empty())
p->next = curLevel.front();
else
p->next = NULL;
}//while
}//while
}
};