Given a singly linked list where elements is 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 rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicTreeNode Sortedlisttobst (ListNode head) {if(head==NULL)return NULL; intLen=0; ListNode node=Head; while(node!=NULL) {node=Node.next; Len++; } returnGetbst (head,0,len-1); } TreeNode Getbst (ListNode head,intStartintend) { if(Start>end)return NULL; intMid= (start+end)/2; ListNode Temp=Head; for(inti=start;i<mid;i++) {//Finding the middle node method ———— start to midtemp=Temp.next; } TreeNode Node=NewTreeNode (Temp.val); Node.left=getbst (head,start,mid-1); Node.right=getbst (Temp.next,mid+1,end);//note the head node of the list of nodes on the right!!! Because the array is not the same way to find the middle node, the list is mainly to traverse, to find the relative position returnnode; }}
[Leedcode 109] Convert Sorted List to Binary Search Tree