Leetcode|BST修改与构造|108. 将有序数组转换为BST

2021-09-18 15:24:53 浏览数 (1)

分治法-递归

代码语言:javascript复制
/**
 * 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:
    void recursive(vector<int>& nums, TreeNode* root, int left, int right) {
        if (left > right) return;
        int mid = (left   right) / 2;
        root->val = nums[mid];
        if (left < mid)
            root->left = new TreeNode(nums[(left   mid) / 2]);
        if (mid < right)
            root->right = new TreeNode(nums[(mid   right) / 2]);
        recursive(nums, root->left, left, mid - 1);
        recursive(nums, root->right, mid   1, right);
    }
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if (nums.empty()) return nullptr;
        TreeNode* root = new TreeNode(0);
        recursive(nums, root, 0, nums.size() - 1);
        return root; 
    }
};

0 人点赞