您的位置:首页 > 其它

Leetcode 108 Convert Sorted Array to Binary Search Tree

2013-02-21 22:02 387 查看
//L108

//we could use d&c

//Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

//we could do it recursively

//pick the middle element as the root

//then pass the left to the sortedArrayToBST, the array is from 0 to mid-1

//pass the right to sortedArrayToBST, the array is from mid+1 the end

//when the str is empty, return NULL

class Solution
{
public:
TreeNode* sortedArrayToBSTHelper(int* arr, int start, int end)
{
if (start <= end)
{
int len = end - start;
int mid = start + len / 2;

TreeNode* root = new TreeNode(arr[mid]);
root->left = sortedArrayToBSTHelper(arr, start, mid - 1);
root->right = sortedArrayToBSTHelper(arr, mid + 1, end);
return root;
}
else
return NULL;
}
TreeNode* sortedArrayToBST(vector<int> &num)
{
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (num.empty())
return NULL;
int arr[num.size()];
for (unsigned int i = 0; i < num.size(); i++)
{
arr[i] = num[i];
}
return sortedArrayToBSTHelper(arr, 0, num.size() - 1);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: