class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num) {
return create(num,0,num.size()-1);
}
TreeNode* create(vector<int>num,int L,int R)
{
if(L>R)return NULL;
int mid=(R+L+1)/2;
//BST树总是从左到右排满的,如果不优先选右边的这个,{1,3}结果为{1,#,3},而实际结果应为{3,1}
TreeNode*root=new TreeNode(num[mid]);
root->left=create(num,L,mid-1);
root->right=create(num,mid+1,R);
return root;
}
};
网友评论