Easy to understand c++ solution


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

Log in to reply
 

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