-
Notifications
You must be signed in to change notification settings - Fork 0
/
L109.java
61 lines (48 loc) · 1.26 KB
/
L109.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
54
55
56
57
58
59
60
61
package Algorithm;
import java.util.ArrayList;
import java.util.List;
public class L109 {
public class ListNode{
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
/*
* 递归循环,最好排除middle点处理,这样思路清晰。
因为是排好序的链表,从中间取根节点能保证平衡二叉搜索树。
*/
public TreeNode sortedListToBST(ListNode head) {
if(head == null) {
return null;
}
List<TreeNode> treeNodeList = new ArrayList<L109.TreeNode>();
while(head != null) {
treeNodeList.add(new TreeNode(head.val));
head = head.next;
}
return sortListToBSTHelper(treeNodeList, 0, treeNodeList.size() - 1);
}
public TreeNode sortListToBSTHelper(List<TreeNode> list, int from, int end) {
if(end == from)
return list.get(end);
else if (end < from) {
return null;
}
int middle = from + (end - from) / 2;
TreeNode leftTree = sortListToBSTHelper(list, from, middle - 1);
TreeNode rightTree = sortListToBSTHelper(list, middle + 1, end);
list.get(middle).left = leftTree;
list.get(middle).right = rightTree;
return list.get(middle);
}
}