原题网址:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
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; }
* }
*/
public class Solution {
private TreeNode build(int[] nums, int from, int to) {
if (from>to) return null;
int m = (from+to)/2;
TreeNode root = new TreeNode(nums[m]);
root.left = build(nums, from, m-1);
root.right = build(nums, m+1, to);
return root;
}
public TreeNode sortedArrayToBST(int[] nums) {
return build(nums, 0, nums.length-1);
}
}