Javascript solution using recursion


  • 0
    S
    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {number[]} nums
     * @return {TreeNode}
     */
    var sortedArrayToBST = function(nums) {
        if (nums.length === 0) { return null; }
        return helper(nums, 0, nums.length - 1);
    };
    
    var helper = function(nums, start, end) {
        if (start === end - 1) {
            var root = new TreeNode(nums[end]);
            root.left = new TreeNode(nums[start]);
            return root;
        }
        if (start === end) { return new TreeNode(nums[start]); }
        
        var mid = getMid(nums, start, end);
        var root = new TreeNode(nums[mid]);
        root.left = helper(nums, start, mid - 1);
        root.right = helper(nums, mid + 1, end);
        
        return root;
    };
    
    var getMid = function(nums, start, end) {
        var slow = start, fast = start;
        while (fast <= end - 1) {
            fast += 2;
            slow++;
        }
        
        return slow;
    };
    

Log in to reply
 

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