Easy understanding c++ recursive solution


  • 1
    H
    class Solution {
    public:
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            return helper(nums, 0, nums.size() - 1);
        }
        TreeNode* helper(vector<int>& nums, int start, int end) {
            if (start > end) return NULL;
            int mid = (start + end)/2;
            TreeNode* node = new TreeNode(nums[mid]);
            node->left = helper(nums, start, mid-1);
            node->right = helper(nums, mid + 1, end);
            return node;
        }
    };

  • 0

    @haoranc What a coincidence! Exactly the same code... dude...

    class Solution {
    private:
        TreeNode *convert(vector<int>& nums, int l, int r)
        {
            if(l > r) return NULL;
            int m = l+(r-l)/2;
            TreeNode *root = new TreeNode(nums[m]);
            if(l == r) return root;
            root->left = convert(nums, l, m-1);
            root->right = convert(nums, m+1, r);
            return root;
        }
    public:
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            return convert(nums, 0, nums.size()-1);
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.