-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConvertSortedListtoBinarySearchTree.java
65 lines (55 loc) · 1.79 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
62
63
64
65
/*
* Key point: fast/slow runner technique to find middle node,
* time complexity is O(nlgn) which comes from f(n) = 2f(n/2) + cn
*
* There is a O(n) solution that build the BST bottom-up
* but it's hard to be implemented in java because of lacking passing by reference
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head==null)
return null;
if(head.next==null)
return new TreeNode(head.val);
//init fast runner and slow runner
ListNode fast=head.next.next;
ListNode slow=head;
//partition the list from the middle, use the fast/slow runner technique
//the slow pointer will be the prev of the middle node
while(fast!=null && fast.next!=null)
{
fast=fast.next.next;
slow=slow.next;
}
//find the middle node
ListNode parent=slow.next;
//partition the list into left and right sublist
slow.next=null;
ListNode left=head;
ListNode right=parent.next;
parent.next=null;
//make the middle node as the root, then apply the function
//to the left part and the right part recursively
TreeNode root=new TreeNode(parent.val);
root.left=sortedListToBST(left);
root.right=sortedListToBST(right);
return root;
}
}