8000 update 109 · githubniraj/Leetcode@de2c09a · GitHub
[go: up one dir, main page]

Skip to content

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

8000
Appearance settings

Commit de2c09a

Browse files
update 109
1 parent 12f1e6b commit de2c09a

File tree

2 files changed

+10
-17
lines changed
  • src
    • main/java/com/fishercoder/solutions/firstthousand
    • test/java/com/fishercoder/firstthousand

2 files changed

+10
-17
lines changed

src/main/java/com/fishercoder/solutions/firstthousand/_109.java

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,7 @@
44
import com.fishercoder.common.classes.TreeNode;
55

66
public class _109 {
7-
87
public static class Solution1 {
9-
108
public TreeNode sortedListToBST(ListNode head) {
119
return toBstRecursively(head, null);
1210
}
@@ -15,16 +13,16 @@ public TreeNode toBstRecursively(ListNode start, ListNode end) {
1513
if (start == end) {
1614
return null;
1715
} else {
18-
ListNode mid = start;
16+
ListNode slow = start;
1917
ListNode fast = start;
20-
while (fast != end && fast.next != end) {
21-
mid = mid.next;
18+
while (fast != end && fast.next != end) {//here is the key: we check if fast != end, not fast != null
19+
slow = slow.next;
2220
fast = fast.next.next;
2321
}
2422

25-
TreeNode root = new TreeNode(mid.val);
26-
root.left = toBstRecursively(start, mid);
27-
root.right = toBstRecursively(mid.next, end);
23+
TreeNode root = new TreeNode(slow.val);
24+
root.left = toBstRecursively(start, slow);
25+
root.right = toBstRecursively(slow.next, end);
2826
return root;
2927
}
3028
}

src/test/java/com/fishercoder/firstthousand/_109Test.java

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,8 @@
55
import com.fishercoder.common.utils.LinkedListUtils;
66
import com.fishercoder.common.utils.TreeUtils;
77
import com.fishercoder.solutions.firstthousand._109;
8-
import org.junit.Before;
9-
import org.junit.BeforeClass;
10-
import org.junit.Test;
8+
import org.junit.jupiter.api.BeforeEach;
9+
import org.junit.jupiter.api.Test;
1110

1211
import java.util.Arrays;
1312

@@ -16,15 +15,11 @@ public class _109Test {
1615
private static ListNode head;
1716
private static TreeNode expected;
1817

19-
@BeforeClass
20-
public static void setup() {
18+
@BeforeEach
19+
public void setup() {
2120
solution1 = new _109.Solution1();
2221
}
2322

24-
@Before
25-
public void setUp() throws Exception {
26-
}
27-
2823
@Test
2924
public void test1() {
3025
head = LinkedListUtils.contructLinkedList(new int[]{1, 2, 3, 4, 5});

0 commit comments

Comments
 (0)
0