-
Notifications
You must be signed in to change notification settings - Fork 3
/
lc109.java
53 lines (51 loc) · 1.26 KB
/
lc109.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
41
42
43
44
45
46
47
48
49
50
51
52
53
// Given a singly linked list where elements are sorted in ascending order,
// convert it to a height balanced BST.
/**
* 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 {
private ListNode cur;
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
ListNode dummy = new ListNode(0);
dummy.next = head;
int len = 0;
while(dummy.next != null){
len++;
dummy = dummy.next;
}
cur = head;
return helper(0, len - 1);
}
private TreeNode helper(int lo, int hi){
if (lo > hi || cur == null) return null;
else if (lo == hi) {
int val = cur.val;
cur = cur.next;
return new TreeNode(val);
}
else {
int mid = (lo + hi)/2;
TreeNode left = helper(lo, mid - 1);
TreeNode root = new TreeNode(cur.val);
root.left = left;
cur = cur.next;
root.right = helper(mid + 1, hi);
return root;
}
}
}