File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff 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+
You can’t perform that action at this time.
0 commit comments