diff --git a/problems/0116.填充每个节点的下一个右侧节点指针.md b/problems/0116.填充每个节点的下一个右侧节点指针.md index ca36ac6f..98bd4e41 100644 --- a/problems/0116.填充每个节点的下一个右侧节点指针.md +++ b/problems/0116.填充每个节点的下一个右侧节点指针.md @@ -169,6 +169,56 @@ class Solution { } ``` +```Java +// 迭代法 +class Solution { + public Node connect(Node root) { + if (root == null) { + return root; + } + + Queue 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 +