Skip to content

Commit d062599

Browse files
109. Convert Sorted List to Binary Search Tree (java)
1 parent 4ab7a26 commit d062599

File tree

1 file changed

+19
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)