Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
思路:既然数组里的元素已经按升序排好序了,那么不难想到用二分法来做这道题。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode sortedArrayToBST(int[] nums) { if (nums.length==0) return null; TreeNode T; return T = binary(nums,0,nums.length-1); } private TreeNode binary(int[] nums,int p,int r){ TreeNode T = null; if (r-p>=0){ int q = (p+r)/2; T = new TreeNode(nums[q]); T.left = binary(nums,p,q-1); T.right = binary(nums,q+1,r); } return T; } }