mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
添加0116.填充每个节点的下一个右侧节点指针.md Java代码
This commit is contained in:
@ -169,6 +169,56 @@ class Solution {
|
||||
}
|
||||
```
|
||||
|
||||
```Java
|
||||
// 迭代法
|
||||
class Solution {
|
||||
public Node connect(Node root) {
|
||||
if (root == null) {
|
||||
return root;
|
||||
}
|
||||
|
||||
Queue<Node> queue = new LinkedList<>();
|
||||
|
||||
queue.add(root);
|
||||
|
||||
while (!queue.isEmpty()) {
|
||||
int size = queue.size();
|
||||
|
||||
// 每层的第一个节点
|
||||
Node cur = queue.poll();
|
||||
if (cur.left != null) {
|
||||
queue.add(cur.left);
|
||||
}
|
||||
if (cur.right != null) {
|
||||
queue.add(cur.right);
|
||||
}
|
||||
|
||||
// 因为已经移除了每层的第一个节点,所以将 0 改为 1
|
||||
while (size-- > 1) {
|
||||
Node next = queue.poll();
|
||||
|
||||
if (next.left != null) {
|
||||
queue.add(next.left);
|
||||
}
|
||||
if (next.right != null) {
|
||||
queue.add(next.right);
|
||||
}
|
||||
|
||||
// 当前节点指向同层的下一个节点
|
||||
cur.next = next;
|
||||
// 更新当前节点
|
||||
cur = next;
|
||||
}
|
||||
|
||||
// 每层的最后一个节点不指向 null 在力扣也能过
|
||||
cur.next = null;
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Python
|
||||
|
||||
```python
|
||||
@ -443,3 +493,4 @@ public class Solution
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
</a>
|
||||
|
||||
|
Reference in New Issue
Block a user