Populating Next Right Pointers in Each Node

https://leetcode.com/problems/populating-next-right-pointers-in-each-node/

 1 /**
 2  * Definition for binary tree with next pointer.
 3  * struct TreeLinkNode {
 4  *  int val;
 5  *  TreeLinkNode *left, *right, *next;
 6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     void connect(TreeLinkNode *root) {
12         queue<TreeLinkNode *> q;
13         if(root==NULL)
14             return;
15         q.push(root);
16         while(!q.empty())
17         {
18             TreeLinkNode * tail=NULL;
19             queue<TreeLinkNode *> q2;
20             while(!q.empty())
21             {
22                 TreeLinkNode * temp=q.front();
23                 q.pop();
24                 if(temp->left!=NULL)
25                     q2.push(temp->left);
26                 if(temp->right!=NULL)
27                     q2.push(temp->right);
28                 if(tail!=NULL)
29                 {
30                     tail->next=temp;
31                 }
32                 tail=temp;
33             }
34             q=q2;
35         }
36     }
37 };
原文地址:https://www.cnblogs.com/aguai1992/p/4632626.html