## Convert Sorted List to Binary Search Tree

### 描述

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

### 分治法，自顶向下

// Convert Sorted List to Binary Search Tree
// 二分法，类似于 Convert Sorted Array to Binary Search Tree，
// 自顶向下，时间复杂度O(nlogn)，空间复杂度O(logn)
class Solution {
public TreeNode sortedListToBST (ListNode head) {

TreeNode root = new TreeNode(mid.val);
root.right = sortedListToBST(mid.next);

return root;
}

while(fast != null && fast.next != null){
prev_slow = slow;
slow = slow.next;
fast = fast.next.next;
}

prev_slow.next = null;
return slow;
}
}

### 自底向上

// Convert Sorted List to Binary Search Tree
// bottom-up，时间复杂度O(n)，空间复杂度O(logn)
public class Solution {
int len = 0;
while (p != null) {
len++;
p = p.next;
}
return sortedListToBST(new Container(head), 0, len - 1);
}
private static TreeNode sortedListToBST(Container list, int start, int end) {
if (start > end) return null;

int mid = start + (end - start) / 2;
TreeNode leftChild = sortedListToBST(list, start, mid - 1);
TreeNode parent = new TreeNode(list.p.val);
parent.left = leftChild;
list.p = list.p.next;
parent.right = sortedListToBST(list, mid + 1, end);
return parent;
}
// 模拟二级指针
static class Container {
ListNode p;
public Container(ListNode p) {
this.p = p;
}
}
}
{"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}