108 Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Solution:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
int n = nums.size();
if ( n == 0 ) return NULL;
TreeNode *root = new TreeNode(nums[n/2]);
vector<int> left(nums.begin(), nums.begin() + n/2);
vector<int> right(nums.begin()+n/2+1, nums.end());
root->left = sortedArrayToBST(left);
root->right = sortedArrayToBST(right);
return root;
}
};
Notes
Note the syntax to create a sub-vector:
// create a vector from nums[n1] to nums[n2-1]
vector<int> left(nums.begin() + n1, nums.begin() + n2);