将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
/**
* 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) {
if(nums.empty()) return NULL;
TreeNode* root = new TreeNode(0);
int t=nums.size();
if(t == 1) {
root->val=nums[0];
return root;
}
if(t==2)
{
root->val=nums[1];
root->left=new TreeNode(nums[0]);
//cout<<root->val<<endl;
return root;
}
if(t==3)
{
root->val=nums[1];
root->left=new TreeNode(nums[0]);
root->right=new TreeNode(nums[2]);
return root;
}
t=t/2;
vector<int>n1(nums.begin(),nums.begin()+t),n2(nums.begin()+t+1,nums.end());
//cout<<n1.size()<<endl;
// cout<<n2.size()<<endl;
root->val=nums[t];
root->left=sortedArrayToBST(n1);
root->right=sortedArrayToBST(n2);
return root;
}
};