Posted on

Description

Submission

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if(nums.empty()) return NULL;
        return util(nums, 0, nums.size() - 1);
    }

private:
    TreeNode* util(vector<int>& nums, int l, int r) {
        if(l > r) return NULL;
        int m = (l + r) / 2;
        TreeNode* root = new TreeNode(nums[m]);
        root->left = util(nums, l, m - 1);
        root->right = util(nums, m + 1, r);
        return root;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *