-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertSortedListToBinarySearchTree.java
More file actions
43 lines (39 loc) · 1.04 KB
/
ConvertSortedListToBinarySearchTree.java
File metadata and controls
43 lines (39 loc) · 1.04 KB
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
41
42
43
/**
* 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; }
* }
*/
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null) return null;
if(head.next == null) return new TreeNode(head.val);
ListNode middle = getMid(head);
TreeNode root = new TreeNode(middle.next.val);
ListNode tmp = middle.next.next;
middle.next = null;
root.left = sortedListToBST(head);
root.right = sortedListToBST(tmp);
return root;
}
public ListNode getMid(ListNode head){
ListNode slow = head;
ListNode fast = head.next == null ? null : head.next.next;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}