/** * 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 == NULL) return; queue<TreeLinkNode *>q; //对列,宽度优先访问 q.push(root); int h=1,h1=1; //h代表当前高度的元素数,h1记录下一层元素个数 while(!q.empty()){ h=h1; h1=0; TreeLinkNode *temp=q.front(); q.pop(); while(h>1){ //处理除了最右一个元素的其他元素 temp->next=q.front(); q.pop(); if(temp->left) {q.push(temp->left);h1++;} if(temp->right) {q.push(temp->right);h1++;} temp=temp->next; h--; } temp->next=NULL; //处理最右边的元素 if(temp->left) {q.push(temp->left);h1++;} if(temp->right) {q.push(temp->right);h1++;} } } };