1
+ /*
2
+ Given the head of a singly linked list where elements are sorted in ascending
3
+ order, convert it to a height balanced BST.
4
+
5
+ For this problem, a height-balanced binary tree is defined as a binary tree in
6
+ which the depth of the two subtrees of every node never differ by more than 1.
7
+
8
+ Example 1:
9
+ Input: head = [-10,-3,0,5,9]
10
+ Output: [0,-3,9,-10,null,5]
11
+ Explanation: One possible answer is [0,-3,9,-10,null,5], which represents
12
+ the shown height balanced BST.
13
+
14
+ Example 2:
15
+ Input: head = []
16
+ Output: []
17
+
18
+ Example 3:
19
+ Input: head = [0]
20
+ Output: [0]
21
+
22
+ Example 4:
23
+ Input: head = [1,3]
24
+ Output: [3,1]
25
+
26
+
27
+ Constraints:
28
+ The number of nodes in head is in the range [0, 2 * 10^4].
29
+ -10^5 <= Node.val <= 10^5
30
+ */
31
+ class Solution {
32
+ public TreeNode sortedListToBST (ListNode head ) {
33
+ if (head == null ){
34
+ return null ;
35
+ }
36
+ ListNode head2 = head ;
37
+ int length = 0 ;
38
+ while (head2 != null ){
39
+ length ++;
40
+ head2 = head2 .next ;
41
+ }
42
+ return sortedListToBSTHelper (head , length );
43
+ }
44
+
45
+ private TreeNode sortedListToBSTHelper (ListNode head , int length ){
46
+ if (length == 0 ){
47
+ return null ;
48
+ } else if (length == 1 ){
49
+ return new TreeNode (head .val );
50
+ }
51
+ // find mid-node and make it a head
52
+ int mid_length = length / 2 ;
53
+ ListNode temp = head ;
54
+ for (int i = 0 ; i < mid_length - 1 ; i ++){
55
+ temp = temp .next ;
56
+ }
57
+ // split LinkedList into two
58
+ ListNode rightTree = temp .next ;
59
+ temp .next = null ;
60
+
61
+ TreeNode root = new TreeNode (rightTree .val );
62
+ rightTree = rightTree .next ;
63
+ root .left = sortedListToBSTHelper (head , mid_length );
64
+ root .right = sortedListToBSTHelper (rightTree , length - 1 - mid_length );
65
+ return root ;
66
+ }
67
+ }
0 commit comments