初步想到用二分法
有序数组,取中点作为root, 分成左片段和右片段,对应左子树和右子树。
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.empty()) return NULL;
//runtime error: reference binding to null pointer of type 'value_type' (stl_vector.h)
int l=0, r=nums.size()-1;
int mid=l+(r-l)/2;
TreeNode* root=new TreeNode(nums[mid]);
Tree(root,l,mid,r,nums);
return root;
}
void Tree(TreeNode* root,int l,int mid,int r,vector<int>& nums){
if(l<=mid-1){
int mid_l=l+(mid-1-l)/2;
root->left=new TreeNode(nums[mid_l]);
Tree(root->left,l,mid_l,mid-1,nums);
}
if(mid+1<=r){
int mid_r=mid+1+(r-mid-1)/2;
root->right=new TreeNode(nums[mid_r]);
Tree(root->right,mid+1,mid_r,r,nums);
}
}
};
下面这种解法没有拆出递归函数,
注意vector的定义方法。