forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertSortedListToBinarySearchTree.java
More file actions
47 lines (46 loc) · 1.28 KB
/
ConvertSortedListToBinarySearchTree.java
File metadata and controls
47 lines (46 loc) · 1.28 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
44
45
46
47
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//O(N)
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
int size = 0;
ListNode cur = head;
while(cur != null){
++size;
cur = cur.next;
}
ListNode[] wrapper = new ListNode[1];
wrapper[0] = head;
return sortedListToBST(wrapper, 0, size - 1);
}
public TreeNode sortedListToBST(ListNode[] head, int min, int max){
if(min <= max){
int mid = (max + min) / 2;
TreeNode leftTree = sortedListToBST(head, min, mid - 1);
TreeNode midTree = new TreeNode(head[0].val);
head[0] = head[0].next;
midTree.left = leftTree;
midTree.right = sortedListToBST(head, mid + 1, max);
return midTree;
}
else
return null;
}
}