题目:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
解答:
对于BTS二叉搜索树来说,若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值。即小的值在左边,大的值在右边
BTS优点:
易获得最大值、最小值、某元素的前驱、某元素的后继
最大值即树的最右节点,最小值即树的最左节点
某元素前驱为左子树的最右,某元素的后继为右子树的最左
因此对于本题来说,即通过二分查找,找出排序数组的中点即为BTS树的根节点,然后用递归分别生成左子树(左半边数组)及右子树(右半边数组)
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums==null){
return null;
}
return sortedArrayToBST(0,nums.length-1,nums);
}
private TreeNode sortedArrayToBST(int start,int end,int[] nums){
if(start<=end){
int middle=(start+end)/2;
TreeNode node=new TreeNode(nums[middle]);
node.left=sortedArrayToBST(start,middle-1,nums);
node.right=sortedArrayToBST(middle+1,end,nums);
return node;
}else{
return null;
}
}
}