Skip to content

Commit b34fb65

Browse files
Merge pull request #2673 from HardX8/insert
添加0116.填充每个节点的下一个右侧节点指针.md Java代码
2 parents f64a164 + 5fc9aa6 commit b34fb65

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

problems/0116.填充每个节点的下一个右侧节点指针.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,56 @@ class Solution {
169169
}
170170
```
171171

172+
```Java
173+
// 迭代法
174+
class Solution {
175+
public Node connect(Node root) {
176+
if (root == null) {
177+
return root;
178+
}
179+
180+
Queue<Node> queue = new LinkedList<>();
181+
182+
queue.add(root);
183+
184+
while (!queue.isEmpty()) {
185+
int size = queue.size();
186+
187+
// 每层的第一个节点
188+
Node cur = queue.poll();
189+
if (cur.left != null) {
190+
queue.add(cur.left);
191+
}
192+
if (cur.right != null) {
193+
queue.add(cur.right);
194+
}
195+
196+
// 因为已经移除了每层的第一个节点,所以将 0 改为 1
197+
while (size-- > 1) {
198+
Node next = queue.poll();
199+
200+
if (next.left != null) {
201+
queue.add(next.left);
202+
}
203+
if (next.right != null) {
204+
queue.add(next.right);
205+
}
206+
207+
// 当前节点指向同层的下一个节点
208+
cur.next = next;
209+
// 更新当前节点
210+
cur = next;
211+
}
212+
213+
// 每层的最后一个节点不指向 null 在力扣也能过
214+
cur.next = null;
215+
}
216+
217+
return root;
218+
}
219+
}
220+
```
221+
172222
### Python
173223

174224
```python
@@ -443,3 +493,4 @@ public class Solution
443493
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
444494
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
445495
</a>
496+

0 commit comments

Comments
 (0)