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) {
return constructBST(head);
}
public TreeNode constructBST(ListNode head){
if(head==null) return null;
if(head.next==null) return new TreeNode(head.val);
ListNode fast=head;
ListNode slow=head;
ListNode prev=null;
while(fast!=null && fast.next!=null){
fast=fast.next.next;
prev=slow;
slow=slow.next;
}
if(prev!=null) prev.next=null;
TreeNode tree=new TreeNode(slow.val);
tree.left=constructBST(head);
tree.right=constructBST(slow.next);
return tree;
}
}