Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
思路:和链表转化成平衡二叉树的思路一样,不过数组找中间位置比较简单
[cpp] view plain copy
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& num)
{
if (num.empty())
{
return NULL;
}
return vecToBST(0, num.size()-1, num);
}
TreeNode* vecToBST(int low, int high, vector<int> v)
{
int mid;
mid = (low+high+1)/2;//找中间位置
TreeNode* root = new TreeNode(v[mid]);
if (mid-1>=low)
{
root->left= vecToBST(low, mid-1, v);
}
if (mid+1<=high)
{
root->right = vecToBST(mid+1, high, v);
}
return root;
}
};