simple C++ solution beats 90%


  • 0
    T
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if(nums.empty()) return NULL;
        return array2bst(nums, 0, nums.size() - 1);
    }
    TreeNode* array2bst(vector<int>& nums, int start, int end) {
        if(start == end && end != nums.size() - 1) return NULL;
        int i = (start+end)/2;
        TreeNode* n = new TreeNode(nums.at(i));
        n->left = start == i ? NULL : array2bst(nums, start, i);
        n->right = end == i ? NULL : array2bst(nums, i+1, end);
        return n;
    }

Log in to reply
 

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