题目链接:108. 将有序数组转换为二叉搜索树 - 力扣(LeetCode)
取中间的数作为根节点,左边的数递归转换,右边的数递归转换
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &nums) {
return build(nums, 0, nums.size() - 1);
}
TreeNode *build(vector<int> &nums, int left, int right) {
if (left > right)
return nullptr;
int root = (left + right) / 2;
return new TreeNode(nums[root], build(nums, left, root - 1), build(nums, root + 1, right));
}
};