leetcode117

This question and leetcode116 difference is that the title is a complete binary tree 116, this question is an ordinary binary tree (not necessarily the complete binary tree).

But I had to do 116 questions of, and did not use the full binary tree this condition, so the original solution, fully applicable to this question.

 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 };

 

Guess you like

Origin www.cnblogs.com/asenyang/p/12021690.html