Array和List的区别在于前者可以随机访问,而后者只能顺序访问。对于把排好序的array转成BST,可以用top-down的方式,很直观也很自然,时间复杂度是O(n)。而对于List如果采用同样的方式,每次需要顺序遍历到中间节点,时间复杂度变成O(nlogn),如果换一种思路,down-top,每次把左子树给先生成,然后是根节点,然后再是右子树,则不需要顺序遍历到中间节点,其时间复杂度就降到O(n),下面是两种情况的AC代码:
1 /** 2 * Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 3 * list can be accessed in order only 4 * @param head 5 * @return 6 */ 7 public TreeNode sortedListToBST(ListNode head){ 8 if(head == null) 9 return null; 10 int len = 0; 11 ListNode temp = head; 12 while(temp != null){ 13 len ++ ; 14 temp = temp.next; 15 } 16 myHead = head; 17 return downUpList2BST( 0 , len-1); 18 } 19 ListNode myHead; 20 private TreeNode downUpList2BST( int start, int end){ 21 if(start>end) 22 return null; 23 int mid = (start+end)/2; 24 TreeNode left = downUpList2BST( start, mid-1); 25 TreeNode root = new TreeNode(myHead.val); 26 root.left = left; 27 myHead = myHead.next; 28 root.right = downUpList2BST(mid+1,end); 29 return root; 30 } 31 /** 32 * array can be accessed randomly 33 * Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 34 * @param num 35 * @return 36 */ 37 public TreeNode sortedArrayToBST(int[] num){ 38 if(num == null || num.length<=0) 39 return null; 40 return recSA2BST(0,num.length-1,num); 41 } 42 /** 43 * 44 * @param start [ 45 * @param end ] 46 * @param num 47 * @return 48 */ 49 private TreeNode recSA2BST(int start, int end, int[] num){ 50 if(start > end) 51 return null; 52 if(start == end) 53 { 54 TreeNode temp = new TreeNode(num[start]); 55 return temp; 56 } 57 int mid = (start+end)/2; 58 TreeNode root = new TreeNode(num[mid]); 59 root.left = recSA2BST(start, mid-1, num); 60 root.right = recSA2BST(mid+1,end,num); 61 return root; 62 }