forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_109.java
33 lines (27 loc) · 888 Bytes
/
_109.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
package com.fishercoder.solutions;
import com.fishercoder.common.classes.ListNode;
import com.fishercoder.common.classes.TreeNode;
/**
* Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
*/
public class _109 {
public TreeNode sortedListToBST(ListNode head) {
return rec(head, null);
}
public TreeNode rec(ListNode start, ListNode end) {
if (start == end) {
return null;
} else {
ListNode mid = start;
ListNode probe = start;
while (probe != end && probe.next != end) {
mid = mid.next;
probe = probe.next.next;
}
TreeNode root = new TreeNode(mid.val);
root.left = rec(start, mid);
root.right = rec(mid.next, end);
return root;
}
}
}