-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathleetcode116-populating-next-right-pointers-in-each-node_bfs_level_order.cpp
68 lines (58 loc) · 1.73 KB
/
leetcode116-populating-next-right-pointers-in-each-node_bfs_level_order.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include<vector>
#include<queue>
#include<algorithm>
#include<iostream>
using namespace std;
/** Definition for a Node. */
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
Node(int _val, Node* _left, Node* _right, Node* _next)
: val(_val), left(_left), right(_right), next(_next) {}
};
class Solution {
public:
Node* connect(Node* root) {
if (root == nullptr)
return nullptr;
if (root->left == NULL && root->right == NULL)
return root;
queue<Node*> q;
q.push({root});
while (!q.empty())
{
vector<Node*> curLevel;
for (int i = q.size(); i > 0; i--)
{
Node* p = q.front();
q.pop();
curLevel.push_back(p);
if (p->left != NULL)
q.push(p->left);
if (p->right != NULL)
q.push(p->right);
}
int curSize = curLevel.size();
for (int i = 0; i < curSize - 1; i++) /* 设置每一层的node的next指针的指向 */
curLevel[i]->next = curLevel[i+1];
curLevel.back()->next = nullptr; /* 将当前层最后一个Node的next设为null */
}
return root;
}
};
// Test
int main()
{
Solution sol;
Node *root = new Node(1);
root->left = NULL;
root->right = new Node(2);
root->right->left = new Node(3);
auto res = sol.connect(root);
return 0;
}