forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsortedlisttobst.java
More file actions
executable file
·65 lines (58 loc) · 1.52 KB
/
sortedlisttobst.java
File metadata and controls
executable file
·65 lines (58 loc) · 1.52 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* 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; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] num, int start, int end){
if(num==null || num.length==0 || start>end){
return null;
}
if(start==end){
TreeNode tn = new TreeNode(num[start]);
tn.left = null;
tn.right = null;
return tn;
}
int mid = start + (end-start)/2;
TreeNode tn = new TreeNode(num[mid]);
tn.left = sortedArrayToBST(num,start,mid-1);
tn.right = sortedArrayToBST(num,mid+1,end);
return tn;
}
public int[] convert(ListNode head){
int length = 0;
ListNode t = head;
while(t!=null){
length++;
t = t.next;
}
int res[] = new int[length];
t = head;
int i=0;
while(t!=null){
res[i] = t.val;
i++;
t = t.next;
}
return res;
}
public TreeNode sortedListToBST(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
int k[] = convert(head);
return sortedArrayToBST(k,0,k.length-1);
}
}