Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
给定一个由小到大排好序的数组,求这个数组对应的平衡二叉查找树,则数组中间位置的值为二叉查找树根节点的值,从数组中间位置(除去中间位置)将数组分为左右两部分,分别生成根节点的左右子树,因为左右子树也都是平衡二叉查找树,因此最直接的方法就是用递归。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return STB(nums,0,nums.size()-1);
}
TreeNode* STB(vector<int>& nums,int low,int high)
{
if(high<low)
return NULL;
int mid=low+(high-low)/2;
TreeNode* root=new TreeNode(nums[mid]);
root->left=STB(nums,low,mid-1);
root->right=STB(nums,mid+1,high);
return root;
}
};