easy to understand solution [14ms]


  • 0
    H
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    
    class Solution {
    public:
        TreeNode* helper(const vector<int> &A, int low, int high)
        {
            if (high < low)
                return nullptr;
            int mid = (low+high+1)/2;
            TreeNode *node = new TreeNode(A[mid]);
            node->left = helper(A, low, mid-1);
            node->right = helper(A, mid+1, high);
            return node;
        }
        
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            int len = nums.size();
            //if (len == 0)
            //    return nullptr;
            return helper(nums, 0, len-1);
        }
    };

Log in to reply
 

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