/**
* 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>> q;
TreeLinkNode *pre = root;
int num = 0;//标记上次访问节点的层数
if(!root)
return;
q.push(pair<TreeLinkNode*,int>(root,1));
while(!q.empty())
{
pair<TreeLinkNode*,int> p = q.front();
q.pop();
if(p.second==num)
pre->next = p.first;
pre = p.first;
num = p.second;
if(p.first->left)
q.push(pair<TreeLinkNode*,int>(p.first->left,(p.second+1)));
if(p.first->right)
q.push(pair<TreeLinkNode*,int>(p.first->right,(p.second+1)));
}
pre = NULL;
}
};
leetcode:Populating Next Right Pointers in Each Node
原文地址:http://blog.csdn.net/majing19921103/article/details/44859239