题目大意:
给出一个二叉树,使得二叉树中每个节点都有一个指针指向其右边的节点。如果节点不存在右边的节点则指针为空。
算法思想:
1.判断根节点是否为空,不空则将更节点和其层号放入队列。
2.当队列不空时,取队头元素cp的并将其移出队列,再取队列一个元素temp.
3.判断temp所记录的节点是否为空且该节点的层号是否和cp的层号相同,如果相同cp的右边节点为temp,否则cp的右边节点为空。
4.判断cp的儿子节点是否为空,不空则入队列。
2.当队列为空时,二叉树转换完毕。
hint:整体算法思想与二叉树的层序遍历思想相似。
代码如下:
/**
* 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) {
queue<pair<TreeLinkNode*,int>> Queue;
pair<TreeLinkNode*,int> cp,temp;
if(root==NULL) return;
Queue.push(make_pair(root,1));
while(!Queue.empty()){
cp=Queue.front();
Queue.pop();
temp=Queue.front();
if(temp.first!=NULL&&temp.second==cp.second){
cp.first->next=temp.first;
}
else
cp.first->next=NULL;
if(cp.first->left!=NULL)
Queue.push(make_pair(cp.first->left,cp.second+1));
if(cp.first->right!=NULL)
Queue.push(make_pair(cp.first->right,cp.second+1));
}
}
};