-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathConvert Sorted List to Binary Search Tree.java
57 lines (56 loc) · 1.34 KB
/
Convert Sorted List to Binary Search Tree.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
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @return: a tree node
*/
private ListNode cur;
public TreeNode sortedListToBST(ListNode head) {
// write your code here
int length = getLength(head);
if (length == 0) {
return null;
}
cur = head;
return buildTree(length);
}
private int getLength(ListNode head) {
int length = 0;
while (head != null) {
length++;
head = head.next;
}
return length;
}
private TreeNode buildTree(int size) {
if (size == 0) {
return null;
}
TreeNode left = buildTree(size / 2);
TreeNode root = new TreeNode(cur.val);
cur = cur.next;
TreeNode right = buildTree(size - 1 - size / 2);
root.left = left;
root.right = right;
return root;
}
}