Leetcode 之Convert Sorted Array to Binary Search Tree(54)

时间:2021-10-28 06:17:43

思路很简单,用二分法,每次选中间的点作为根结点,用左、右结点递归。

Leetcode 之Convert Sorted Array to Binary Search Tree(54)

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;
}