Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
public class Solution { public TreeNode sortedListToBST(ListNode head) { if (head == null) return null; int [] num = getValues(head); return sortedArrayToBST(num); } private int getLength(ListNode head){ int i =0; while(head !=null){ i++; head = head.next; } return i; } private int [] getValues(ListNode head){ int [] result = new int[getLength(head)]; int i=0; while(head != null){ result[i++] = head.val; head = head.next; } return result; } public TreeNode sortedArrayToBST(int[] num) { if(num == null || num.length == 0){ return null;} int len = num.length; return sortedArray(num, 0 ,len-1); } public TreeNode sortedArray(int[] num, int low, int high){ if(low == high){ TreeNode root= new TreeNode(num[low]); return root; } else if(low > high){ return null; } else{ int mid = low + (high- low) /2; TreeNode root = new TreeNode(num[mid]); root.left = sortedArray(num,low,mid-1); root.right = sortedArray(num,mid+1,high); return root; } } }