Leetcode 108 Convert Sorted Array to Binary Search Tree

来源:互联网 发布:爱青岛网络公开课 编辑:程序博客网 时间:2024/04/30 02:41


//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;}elsereturn NULL;}TreeNode* sortedArrayToBST(vector<int> &num){// Start typing your C/C++ solution below// DO NOT write int main() functionif (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);}};