C++ in 8 lines with recursive


  • 0
    Z
    class Solution {
    public:
        TreeNode* buildBST(vector<int>& nums,int start,int end){
            if(start > end )return NULL;
            int mid = start + (end - start )/2 ; 
            TreeNode* root = new TreeNode(nums[mid]);
            root -> left = buildBST(nums,start,mid-1);
            root -> right = buildBST(nums,mid + 1,end);
            return root;
        }
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            return buildBST( 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.