-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
43 lines (38 loc) · 976 Bytes
/
Solution.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
/**
* 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; }
* }
*/
class Solution {
public TreeNode sortedListToBST(ListNode head) {
int length = 0;
ListNode p = head;
while (p != null) {
p = p.next;
length++;
}
return help(head, length);
}
public TreeNode help(ListNode head, int length) {
if (length == 0) return null;
ListNode p = head;
int mid = length / 2;
for (int i = 0; i < mid; i++) p = p.next;
TreeNode root = new TreeNode(p.val);
root.left = help(head, mid);
root.right = help(p.next, length - mid - 1);
return root;
}
}