美文网首页
108. Convert Sorted Array to Bin

108. Convert Sorted Array to Bin

作者: 刘小小gogo | 来源:发表于2018-08-19 23:28 被阅读0次
image.png

类似于二分查找

/**
 * 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 helper(nums, 0, nums.size() - 1);
    }
private:
    TreeNode* helper(vector<int> nums, int l ,int r){
        if(l > r) return NULL;
        int mid = (l + r) / 2;
        TreeNode* root = new TreeNode(nums[mid]);
        root->left = helper(nums, l, mid - 1);
        root->right = helper(nums, mid + 1, r);
        return root;
    }
};

相关文章

网友评论

      本文标题:108. Convert Sorted Array to Bin

      本文链接:https://www.haomeiwen.com/subject/ztwhiftx.html