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 start, int end) {
if (start > end) return null;
int mid = start + end >> 1;
TreeNode root = new TreeNode(nums[mid]);
root.left = build(nums, start, mid-1);
root.right = build(nums, mid+1, end);
return root;
}
public TreeNode sortedArrayToBST(int[] nums) {
return build(nums, 0, nums.length-1);
}
}
LeetCode Convert Sorted Array to Binary Search Tree
原文:http://blog.csdn.net/u011345136/article/details/45506833