Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
主要步骤为:
1、取Middle为根节点
2、前半段递归为left节点
3、后半段递归为right节点
很明显遍历树的变体,上代码:
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null || nums.length == 0) return null;
return sortedArrayToBST(nums, 0, nums.length-1);
}
private TreeNode sortedArrayToBST(int[] nums, int s, int e) {
if (s > e) return null;
int mid = (s+e)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = sortedArrayToBST(nums, s, mid-1);
root.right = sortedArrayToBST(nums, mid+1, e);
return root;
}
私以为,代码还是挺美的!!!