sortedArrayToBST with JavaScript


  • 0
    N
    /**
     * 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) {
          return [];
      }
    
      const recursion = (arr, low, high) => {
        if(low > high) {
          return null;
        }
        let mid = Math.floor((low + high) / 2);
        let bst = new TreeNode(arr[mid]);
    
        bst.left = recursion(arr, low, mid - 1);
        bst.right = recursion(arr, mid + 1, high)
    
        return bst;
      };
    
      return recursion(nums, 0, nums.length - 1);
    };
    

Log in to reply
 

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