给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。
样例
给出数组 [1,2,3,4,5,6,7]
, 返回
4
/
2 6
/ /
1 3 5 7
1 /** 2 * Definition of TreeNode: 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left, right; 6 * public TreeNode(int val) { 7 * this.val = val; 8 * this.left = this.right = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 /** 14 * @param A: an integer array 15 * @return: a tree node 16 */ 17 public TreeNode sortedArrayToBST(int[] A) { 18 // write your code here 19 if(A.length ==0 ) return null; 20 return sortedToBST(A, 0, A.length-1); 21 } 22 public TreeNode sortedToBST(int[] A,int start,int end){ 23 if (start > end) 24 return null; 25 int mid = (start+end)/2; 26 TreeNode root = new TreeNode(A[mid]); 27 root.left = sortedToBST(A,start,mid-1); 28 root.right = sortedToBST(A,mid+1,end); 29 return root; 30 } 31 }