Analysis:
class Solution {
public:
TreeNode *helper(vector &num, int b, int e) {
if (b > e)
return NULL;
else
{
//middle as the root and recursively to construct the tree left and right
int mid = (b+e)/2;
TreeNode* root = new TreeNode(num[mid]);
root->left = helper(num, b, mid - 1);
root->right = helper(num, mid+1, e);
return root;
}
}
TreeNode *sortedArrayToBST(vector &num) {
return helper(num, 0, num.size() - 1);
}
};
No comments:
Post a Comment