Skip to content

Commit 0522cd8

Browse files
refactor 116
1 parent d5335de commit 0522cd8

File tree

1 file changed

+34
-0
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+34
-0
lines changed

src/main/java/com/fishercoder/solutions/_116.java

+34
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
import com.fishercoder.common.classes.TreeLinkNode;
44

5+
import java.util.LinkedList;
6+
import java.util.Queue;
7+
58
public class _116 {
69
public static class Solution1 {
710
/**
@@ -44,4 +47,35 @@ public void connect(TreeLinkNode root) {
4447
}
4548
}
4649
}
50+
51+
public static class Solution2 {
52+
/**
53+
* My complete original solution on 10/10/2021.
54+
*/
55+
public TreeLinkNode connect(TreeLinkNode root) {
56+
if (root == null) {
57+
return null;
58+
}
59+
Queue<TreeLinkNode> queue = new LinkedList<>();
60+
queue.offer(root);
61+
while (!queue.isEmpty()) {
62+
int size = queue.size();
63+
for (int i = 0; i < size; i++) {
64+
TreeLinkNode curr = queue.poll();
65+
if (i < size - 1) {
66+
curr.next = queue.peek();
67+
} else {
68+
curr.next = null;
69+
}
70+
if (curr.left != null) {
71+
queue.offer(curr.left);
72+
}
73+
if (curr.right != null) {
74+
queue.offer(curr.right);
75+
}
76+
}
77+
}
78+
return root;
79+
}
80+
}
4781
}

0 commit comments

Comments
 (0)