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; 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);
ListNode slow = head;
ListNode fast = head;
ListNode temp = null;
while(fast!=null&&fast.next!=null){
fast = fast.next.next;
temp = slow;
slow = slow.next;
}
TreeNode newhead = new TreeNode(slow.val);
if(temp==null){
head = null;
}
else temp.next=null;
newhead.left = sortedListToBST(head);
newhead.right = sortedListToBST(slow.next);
return newhead;
}
}