10 lines concise and easy understand c++ solution


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

Log in to reply
 

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