Skip to content

Commit 4adf872

Browse files
authored
Create Convert Sorted List to Binary Search Tree.java
1 parent 2a0435f commit 4adf872

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public TreeNode sortedListToBST(ListNode head) {
3+
if (head == null)
4+
return null;
5+
return toBST(head, null);
6+
}
7+
public TreeNode toBST(ListNode head, ListNode tail) {
8+
9+
ListNode slow = head;
10+
ListNode fast = head;
11+
if (head==tail) return null;
12+
while (fast!=tail && fast.next!=tail) {
13+
slow = slow.next;
14+
fast = fast.next.next;
15+
}
16+
17+
TreeNode tree = new TreeNode(slow.val);
18+
tree.left = toBST(head, slow);
19+
tree.right = toBST(slow.next, tail);
20+
return tree;
21+
}
22+
}

0 commit comments

Comments
 (0)