@@ -58,7 +58,19 @@ struct Node {
58
58
59
59
<!-- 这里可写通用的实现逻辑 -->
60
60
61
- “BFS 层次遍历”实现。
61
+ ** 方法一:BFS**
62
+
63
+ 使用队列进行层序遍历,每次遍历一层时,将当前层的节点按顺序连接起来。
64
+
65
+ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。
66
+
67
+ ** 方法二:空间优化**
68
+
69
+ 方法一的空间复杂度较高,因为需要使用队列存储每一层的节点。我们可以使用常数空间来实现。
70
+
71
+ 定义两个指针 $prev$ 和 $next$,分别指向下一层的前一个节点和第一个节点。遍历当前层的节点时,把下一层的节点串起来,同时找到下一层的第一个节点。当前层遍历完后,把下一层的第一个节点 $next$ 赋值给 $node$,继续遍历。
72
+
73
+ 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为二叉树的节点个数。
62
74
63
75
<!-- tabs:start -->
64
76
@@ -79,21 +91,54 @@ class Node:
79
91
80
92
81
93
class Solution :
82
- def connect (self , root : ' Node' ) -> ' Node' :
83
- if root is None or (root.left is None and root.right is None ) :
94
+ def connect (self , root : " Node" ) -> " Node" :
95
+ if root is None :
84
96
return root
85
97
q = deque([root])
86
98
while q:
87
- size = len (q)
88
- cur = None
89
- for _ in range (size):
99
+ p = None
100
+ for _ in range (len (q)):
90
101
node = q.popleft()
91
- if node.right:
92
- q.append(node.right)
102
+ if p:
103
+ p.next = node
104
+ p = node
93
105
if node.left:
94
106
q.append(node.left)
95
- node.next = cur
96
- cur = node
107
+ if node.right:
108
+ q.append(node.right)
109
+ return root
110
+ ```
111
+
112
+ ``` python
113
+ """
114
+ # Definition for a Node.
115
+ class Node:
116
+ def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
117
+ self.val = val
118
+ self.left = left
119
+ self.right = right
120
+ self.next = next
121
+ """
122
+
123
+ class Solution :
124
+ def connect (self , root : ' Node' ) -> ' Node' :
125
+ def modify (curr ):
126
+ nonlocal prev, next
127
+ if curr is None :
128
+ return
129
+ next = next or curr
130
+ if prev:
131
+ prev.next = curr
132
+ prev = curr
133
+
134
+ node = root
135
+ while node:
136
+ prev = next = None
137
+ while node:
138
+ modify(node.left)
139
+ modify(node.right)
140
+ node = node.next
141
+ node = next
97
142
return root
98
143
```
99
144
@@ -127,30 +172,90 @@ class Node {
127
172
128
173
class Solution {
129
174
public Node connect (Node root ) {
130
- if (root == null || (root . left == null && root . right == null ) ) {
175
+ if (root == null ) {
131
176
return root;
132
177
}
133
178
Deque<Node > q = new ArrayDeque<> ();
134
179
q. offer(root);
135
180
while (! q. isEmpty()) {
136
- Node cur = null ;
137
- for (int i = 0 , n = q. size(); i < n; ++ i ) {
138
- Node node = q. pollFirst ();
139
- if (node . right != null ) {
140
- q . offer( node. right) ;
181
+ Node p = null ;
182
+ for (int n = q. size(); n > 0 ; -- n ) {
183
+ Node node = q. poll ();
184
+ if (p != null ) {
185
+ p . next = node;
141
186
}
187
+ p = node;
142
188
if (node. left != null ) {
143
189
q. offer(node. left);
144
190
}
145
- node. next = cur;
146
- cur = node;
191
+ if (node. right != null ) {
192
+ q. offer(node. right);
193
+ }
147
194
}
148
195
}
149
196
return root;
150
197
}
151
198
}
152
199
```
153
200
201
+ ``` java
202
+ /*
203
+ // Definition for a Node.
204
+ class Node {
205
+ public int val;
206
+ public Node left;
207
+ public Node right;
208
+ public Node next;
209
+
210
+ public Node() {}
211
+
212
+ public Node(int _val) {
213
+ val = _val;
214
+ }
215
+
216
+ public Node(int _val, Node _left, Node _right, Node _next) {
217
+ val = _val;
218
+ left = _left;
219
+ right = _right;
220
+ next = _next;
221
+ }
222
+ };
223
+ */
224
+
225
+ class Solution {
226
+ private Node prev, next;
227
+
228
+ public Node connect (Node root ) {
229
+ Node node = root;
230
+ while (node != null ) {
231
+ prev = null ;
232
+ next = null ;
233
+ while (node != null ) {
234
+ modify(node. left);
235
+ modify(node. right);
236
+ node = node. next;
237
+ }
238
+ node = next;
239
+ }
240
+ return root;
241
+ }
242
+
243
+ private void modify (Node curr ) {
244
+ if (curr == null ) {
245
+ return ;
246
+ }
247
+ if (next == null ) {
248
+ next = curr;
249
+ }
250
+ if (prev != null ) {
251
+ prev. next = curr;
252
+ }
253
+ prev = curr;
254
+
255
+ }
256
+ }
257
+ ```
258
+
154
259
### ** C++**
155
260
156
261
``` cpp
@@ -175,25 +280,77 @@ public:
175
280
class Solution {
176
281
public:
177
282
Node* connect(Node* root) {
178
- if (!root || (!root->left && !root->right) ) {
283
+ if (!root) {
179
284
return root;
180
285
}
181
- queue<Node* > q;
182
- q.push(root);
286
+ queue<Node* > q{{root}};
183
287
while (!q.empty()) {
184
- Node* cur = nullptr;
185
- for (int i = 0, n = q.size(); i < n; ++i ) {
288
+ Node* p = nullptr;
289
+ for (int n = q.size(); n; --n ) {
186
290
Node* node = q.front();
187
291
q.pop();
188
- if (node->right ) {
189
- q.push(node->right) ;
292
+ if (p ) {
293
+ p->next = node ;
190
294
}
295
+ p = node;
191
296
if (node->left) {
192
297
q.push(node->left);
193
298
}
194
- node->next = cur;
195
- cur = node;
299
+ if (node->right) {
300
+ q.push(node->right);
301
+ }
302
+ }
303
+ }
304
+ return root;
305
+ }
306
+ };
307
+ ```
308
+
309
+ ```cpp
310
+ /*
311
+ // Definition for a Node.
312
+ class Node {
313
+ public:
314
+ int val;
315
+ Node* left;
316
+ Node* right;
317
+ Node* next;
318
+
319
+ Node() : val(0), left(NULL), right(NULL), next(NULL) {}
320
+
321
+ Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
322
+
323
+ Node(int _val, Node* _left, Node* _right, Node* _next)
324
+ : val(_val), left(_left), right(_right), next(_next) {}
325
+ };
326
+ */
327
+
328
+ class Solution {
329
+ public:
330
+ Node* connect(Node* root) {
331
+ Node* node = root;
332
+ Node* prev = nullptr;
333
+ Node* next = nullptr;
334
+ auto modify = [&](Node* curr) {
335
+ if (!curr) {
336
+ return;
337
+ }
338
+ if (!next) {
339
+ next = curr;
340
+ }
341
+ if (prev) {
342
+ prev->next = curr;
343
+ }
344
+ prev = curr;
345
+ };
346
+ while (node) {
347
+ prev = next = nullptr;
348
+ while (node) {
349
+ modify(node->left);
350
+ modify(node->right);
351
+ node = node->next;
196
352
}
353
+ node = next;
197
354
}
198
355
return root;
199
356
}
@@ -214,35 +371,67 @@ public:
214
371
*/
215
372
216
373
func connect (root *Node ) *Node {
217
- if root == nil {
218
- return nil
219
- }
220
- if root.Left != nil && root.Right != nil {
221
- root.Left.Next = root.Right
222
- }
223
- if root.Left != nil && root.Right == nil {
224
- root.Left.Next = getNext(root.Next)
225
- }
226
- if root.Right != nil {
227
- root.Right.Next = getNext(root.Next)
228
- }
229
- //先连接右侧节点
230
- connect(root.Right)
231
- connect(root.Left)
232
- return root
374
+ if root == nil {
375
+ return root
376
+ }
377
+ q := []*Node{root}
378
+ for len (q) > 0 {
379
+ var p *Node
380
+ for n := len (q); n > 0 ; n-- {
381
+ node := q[0 ]
382
+ q = q[1 :]
383
+ if p != nil {
384
+ p.Next = node
385
+ }
386
+ p = node
387
+ if node.Left != nil {
388
+ q = append (q, node.Left )
389
+ }
390
+ if node.Right != nil {
391
+ q = append (q, node.Right )
392
+ }
393
+ }
394
+ }
395
+ return root
233
396
}
397
+ ```
234
398
235
- func getNext(node *Node) *Node {
236
- for node != nil {
237
- if node.Left != nil {
238
- return node.Left
239
- }
240
- if node.Right != nil {
241
- return node.Right
242
- }
243
- node = node.Next
244
- }
245
- return nil
399
+ ``` go
400
+ /* *
401
+ * Definition for a Node.
402
+ * type Node struct {
403
+ * Val int
404
+ * Left *Node
405
+ * Right *Node
406
+ * Next *Node
407
+ * }
408
+ */
409
+
410
+ func connect (root *Node ) *Node {
411
+ node := root
412
+ var prev , next *Node
413
+ modify := func (curr *Node) {
414
+ if curr == nil {
415
+ return
416
+ }
417
+ if next == nil {
418
+ next = curr
419
+ }
420
+ if prev != nil {
421
+ prev.Next = curr
422
+ }
423
+ prev = curr
424
+ }
425
+ for node != nil {
426
+ prev, next = nil , nil
427
+ for node != nil {
428
+ modify (node.Left )
429
+ modify (node.Right )
430
+ node = node.Next
431
+ }
432
+ node = next
433
+ }
434
+ return root
246
435
}
247
436
```
248
437
0 commit comments