recursion programming
1 public class Solution { 2 public TreeNode sortedListToBST(ListNode head) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 if(head == null) 6 return null; 7 ListNode tmp = head; 8 int count = 0; 9 while(tmp !=null){ 10 tmp = tmp.next; 11 count++; 12 } 13 return buildBST(head, count); 14 } 15 16 private TreeNode buildBST(ListNode head, int n) 17 { 18 if(head == null || n==0) 19 return null; 20 if(n == 1) 21 return new TreeNode(head.val); 22 int boundary = n/2; 23 ListNode tmp = head; 24 for(int i = 0; i < boundary; i++) 25 tmp = tmp.next; 26 TreeNode mynode = new TreeNode(tmp.val); 27 mynode.left = buildBST(head, boundary); 28 mynode.right = buildBST(tmp.next, n-boundary-1); 29 return mynode; 30 } 31 }