forked from xiaoyaoworm/Leetcode-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
109_sortedListToBST.java
40 lines (38 loc) · 1 KB
/
109_sortedListToBST.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null) return null;
if(head.next == null) return new TreeNode(head.val);
ListNode slow = head;
ListNode fast = head;
ListNode preSlow = head;
while(fast!=null && fast.next!=null){
preSlow = slow;
slow = slow.next;
fast = fast.next.next;
}
ListNode second = slow.next;
preSlow.next = null;
ListNode first = head;
TreeNode root = new TreeNode(slow.val);
root.left = sortedListToBST(first);
root.right = sortedListToBST(second);
return root;
}
}