-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConvertSortedListToBinarySearchTree.java
61 lines (54 loc) · 1.31 KB
/
ConvertSortedListToBinarySearchTree.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 leetcode;
/**
* 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; }
* }
*/
public class ConvertSortedListToBinarySearchTree {
static ListNode q;
public TreeNode sortedListToBST(ListNode head) {
if(head == null)
return null;
q = head;
int lens = getLength(head);
return sortedListToBST(0,lens - 1);
}
public int getLength(ListNode head)
{
int lens = 0;
ListNode p = head;
if(head == null)
return 0;
while(p != null)
{
++lens;
p = p.next;
}
return lens;
}
public TreeNode sortedListToBST(int start,int end)
{
if(start > end)
return null;
int mid = (start + end) / 2 ;
TreeNode left = sortedListToBST(start,mid - 1);
TreeNode root = new TreeNode(q.val);
q = q.next;
TreeNode right = sortedListToBST(mid+1,end);
root.left = left;
root.right = right;
return root;
}
}