From 5fc9aa68a3f483b41ddae1fe735cfe21a676d7dd Mon Sep 17 00:00:00 2001 From: Hard <2321291138@qq.com> Date: Mon, 5 Aug 2024 17:24:26 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00116.=E5=A1=AB=E5=85=85?= =?UTF-8?q?=E6=AF=8F=E4=B8=AA=E8=8A=82=E7=82=B9=E7=9A=84=E4=B8=8B=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E5=8F=B3=E4=BE=A7=E8=8A=82=E7=82=B9=E6=8C=87=E9=92=88?= =?UTF-8?q?.md=20Java=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...个节点的下一个右侧节点指针.md | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) 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 +