您的位置:首页 > 其它

【convert-sorted-array-to-binary-search-tree 】

2017-09-08 10:12 232 查看
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

思路:和链表转化成平衡二叉树的思路一样,不过数组找中间位置比较简单

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: