LeetCode108. Convert Sorted Array to Binary Search Tree

文章目录

    • 一、题目
    • 二、题解

一、题目

Given an integer array nums where the elements are sorted in ascending order, convert it to a
height-balanced
binary search tree.

Example 1:

Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:

Example 2:

Input: nums = [1,3]
Output: [3,1]
Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.

Constraints:

1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums is sorted in a strictly increasing order.

二、题解

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* makeBST(vector<int>& nums,int left,int right){
        if(left >= right) return nullptr;
        int mid = (left + right) >> 1;
        TreeNode* t = new TreeNode(nums[mid]);
        t->left = makeBST(nums,left,mid);
        t->right = makeBST(nums,mid + 1,right);
        return t;
    }
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        int n = nums.size();
        return makeBST(nums,0,n);
    }
};

你可能感兴趣的:(算法,数据结构,c++,leetcode,树)