Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* 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 Solution {
public TreeNode sortedListToBST(ListNode head) {
return BST(head, null);
}
private TreeNode BST(ListNode head, ListNode tail) {
if (head == tail) {
return null;
}
ListNode slow = head, fast = head;
while (fast != tail && fast.next != tail) {
fast = fast.next.next;
slow = slow.next;
}
TreeNode mid = new TreeNode(slow.val);
mid.left = BST(head, slow);
mid.right = BST(slow.next, tail);
return mid;
}
}