题目:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
题意:
就是给一个递增序列的数组,然后将这个数组转化成一棵平衡的二叉搜索树。
题解:
首先因为是递增的序列,所以很容易想到二分搜索来做,也就是折半查找,因为这样就可以保证是一棵平衡的树。首先平衡的树,是指树的左子树和右子树的树高差要么是-1,0,1。所以可以考虑采用递归来做。这题的思路其实和给定二叉树的先序遍历和中序遍历序列,求这棵二叉树的结构一样。http://blog.youkuaiyun.com/sun_wangdong/article/details/50032287。
public class Solution
{
public TreeNode sortedArrayToBST(int[] nums)
{
return middlesearch(nums,0,nums.length - 1,nums.length);
}
public TreeNode middlesearch(int[] nums,int start,int end,int length)
{
int i = 0,j = 0,value = 0;
if(length == 0)
return null;
if(length % 2 != 0)
{
value = nums[start + length / 2];
i = start + length / 2 - 1;
j = start + length / 2 + 1;
}
else if(length % 2 == 0)
{
if(length / 2 != 0)
{
value = nums[start + length / 2 - 1];
i = start + length / 2 - 2;
j = start + length / 2;
}
else if(length / 2 == 0)
{
value = nums[start + length / 2 + 1];
i = start + 1;
j = start + 1;
}
}
TreeNode root = new TreeNode(value);
root.left = middlesearch(nums,start,i ,i - start + 1);
root.right = middlesearch(nums,j,end,end - j + 1);
return root;
}
}