leetcode 108
class Solution {
public:
TreeNode* Create(vector<int>&nums,int left,int right){
if(left>right){
return NULL;
}
int mid=(left+right)/2;
TreeNode* root=new TreeNode(nums[mid]);
root->left=Create(nums,left,mid-1);
root->right=Create(nums,mid+1,right);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.size()==0)return NULL;
TreeNode* root=Create(nums,0,nums.size()-1);
return root;
}
};
leetcode 109
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
vector<int> vec;
while(head!=NULL){
vec.push_back(head->val);
head=head->next;
}
TreeNode* root=buildtree(vec,0,vec.size()-1);
return root;
}
TreeNode* buildtree(vector<int>& v,int left,int right){
if(left>right){
return NULL;
}
int mid=(left+right)/2;
TreeNode* root=new TreeNode(v[mid]);
root->left=buildtree(v,left,mid-1);
root->right=buildtree(v,mid+1,right);
return root;
}
};