My solution for reference


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

    Thoughts: same as previous question: find out the middle element as current TreeNode. Then solve the problem by recursive.


  • 0
    P

    I think the above algo wont work if there are duplicate numbers.


  • 0
    L

    give me your against example.


Log in to reply
 

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