8ms with C++ solution


  • 0
    M

    class Solution {
    public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
    return creatBST (nums,0,nums.size()-1);
    }

    TreeNode* creatBST(vector<int>& nums,int m,int n)
    {
        if(n<m)
        return NULL;
       TreeNode* newNode=new  TreeNode(nums[(m+n)/2]);
       newNode->left=creatBST(nums,m,(m+n)/2-1);
       newNode->right=creatBST(nums,(m+n)/2+1,n);
       return newNode;
    }
    

    };


  • 0
    V

    Your solution will fail when size of array is even
    Try this: [1,2,3,4,5,6]. It gives wrong answer.


  • 0
    M

    @viveksk I donnot agree with you ,Ihave test It ,My answer is [3,1,5,null,2,4,6],It is a BST;the system answer is [4,2,6,1,3,5],It is a BST too. so my solution has no problem.


Log in to reply
 

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