1 class Solution { 2 public: 3 Node* connect(Node* root) { 4 if (root != NULL) 5 { 6 queue<Node*> Q; 7 root->next = NULL; 8 Q.push(root); 9 while (!Q.empty()) 10 { 11 vector<Node*> V; 12 while (!Q.empty()) 13 { 14 Node* t = Q.front(); 15 Q.pop(); 16 if (t->left != NULL) 17 { 18 V.push_back(t->left); 19 } 20 if (t->right != NULL) 21 { 22 V.push_back(t->right); 23 } 24 } 25 V.push_back(NULL); 26 for (int i = V.size() - 1; i > 0; i--) 27 { 28 V[i - 1]->next = V[i]; 29 } 30 for (int i = 0; i < V.size() - 1; i++) 31 { 32 if (V[i] != NULL) 33 { 34 Q.push(V[i]); 35 } 36 } 37 } 38 } 39 return root; 40 } 41 };