Question:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Answer:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num) {
if(num.size()==0)return NULL;
int len= num.size();
TreeNode *root = ArraytoBSTHelper(num, 0, len-1);
return root;
}
TreeNode *ArraytoBSTHelper(vector<int> &num, int l, int h){
if(l>h) return NULL;
int mid = (l+h)/2;
TreeNode *root = new TreeNode(num[mid]);
root->left = ArraytoBSTHelper(num,l,mid-1);
root->right = ArraytoBSTHelper(num,mid+1,h);
return root;
}
};
No comments:
Post a Comment