Monday, August 28, 2017

108. Convert Sorted Array to Binary Search Tree

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/
Solution 1. (19 ms)
    TreeNode* array2bst(vector<int>& nums, int i, int j) {
        if(i>j) return nullptr;
        int m = (i+j)/2;
        TreeNode* node = new TreeNode(nums[m]);
        node->left = array2bst(nums, i, m-1);
        node->right = array2bst(nums, m+1, j);
        return node;
    }
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return array2bst(nums, 0, nums.size()-1);
    }
Solution 2. (19 ms)
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if(nums.size()==0) return nullptr;
        int m = nums.size()/2;
        TreeNode* node = new TreeNode(nums[m]);
        vector<int> nl(nums.begin(), nums.begin()+m);
        vector<int> nr(nums.begin()+m+1,nums.end());
        node->left = sortedArrayToBST(nl);
        node->right = sortedArrayToBST(nr);
        return node;

    }

No comments:

Post a Comment