思路很简单,用二分法,每次选中间的点作为根结点,用左、右结点递归。
TreeNode* sortedArrayToBST(vector<int> &num)
{
return sortedArrayToBST(num.begin(), num.end());
}
template<typename RandomAccessIterator>
TreeNode* sortedArrayToBST(RandomAccessIterator first, RandomAccessIterator last)
{
const auto length = distance(first, last);
if (length <= )return nullptr; auto mid = first + length / ;
TreeNode *root = new TreeNode(*mid);
root->left = sortedArrayToBST(first, mid);
root->right = sortedArrayToBST(mid, last); return root;
}