117. 填充每个节点的下一个右侧节点指针 II 题目有点类似于层序线索化,就是在层序遍历的基础上魔改一下,使得可以获得当前遍历到第几层的信息。

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
/*
// 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:
void bfs(Node *root) {

if(root == NULL) return ;
queue<Node*> q;
q.push(root);
//cnt:当前正在遍历的这一层已经遍历了几个节点
//tail:当前正在遍历的这一层一共有几个节点
//num:下一层一共有几个节点
//pre:这一层上一个遍历到的节点
int cnt = 0, tail = 1, num = 0;
Node *pre = NULL;
while(!q.empty()) {

Node *u = q.front();
q.pop();
if(pre) pre->next = u;
pre = u;
++ cnt;
if(u->left) {

q.push(u->left);
++ num;
}
if(u->right) {

q.push(u->right);
++ num;
}
if(cnt == tail) {

cnt = 0;
tail = num;
num = 0;
u->next = NULL;
pre = NULL;
}
}
}
Node* connect(Node* root) {

bfs(root);
return root;
}
};

还有一种简单的写法,直接得出当前层节点个数

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
/*
// 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:
void bfs(Node *root) {

if(root == NULL) return ;
queue<Node*> q;
q.push(root);
while(!q.empty()) {

Node *pre = NULL;
int len = q.size(); //为当前层的总节点数
for(int i = 0; i < len; i ++) {
//遍历当前层节点
Node *u = q.front();
q.pop();
if(pre) pre->next = u;
pre = u;
if(u->left) q.push(u->left);
if(u->right) q.push(u->right);
}
}
}
Node* connect(Node* root) {

bfs(root);
return root;
}
};