This is my code to convert a sorted vector of integers to a balanced binary tree of the same content.
The binary tree is made of these nodes:
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
Here's my first attempt:
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.empty()) return NULL;
if(nums.size()==1){
TreeNode* root = new TreeNode(nums[0]);
return root;
}
int mid = nums.size() / 2;
TreeNode* root = new TreeNode(nums[mid]);
vector<int> left(nums.begin(),nums.begin()+mid);
vector<int> right(nums.begin()+mid+1,nums.end());
root->left = sortedArrayToBST(left);
root->right = sortedArrayToBST(right);
return root;
}
};
I was making new vectors and copying contents twice in every recursive call, So this is the optimized version by directly passing iterator instead of passing index and copying sub arrays every time:
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return makeBST(nums.begin(),nums.end());
}
TreeNode* makeBST(vector<int>::iterator start,vector<int>::iterator end){
if( start >= end ) return NULL;
vector<int>::iterator mid = start + (end - start) / 2;
TreeNode* root = new TreeNode(*mid);
root -> left = makeBST( start , mid );
root -> right = makeBST( mid + 1 , end );
return root;
}
};
The second code has much faster run time than first one.
Is there a better way to pass iterators to function?
Any other improvements?