Skip to main content

Leetcode - 108. Convert Sorted Array to Binary Search Tree

· One min read

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

Solution 1

/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {number[]} nums
* @return {TreeNode}
*/
var sortedArrayToBST = function (nums) {
if (nums.length === 0) {
return null;
}
return createBST(nums, 0, nums.length - 1);
};

const createBST = (nums, low, high) => {
if (low > high) {
return null;
}

let mid = Math.floor((high + low) / 2);

let node = new TreeNode(nums[mid]);
node.left = createBST(nums, low, mid - 1);
node.right = createBST(nums, mid + 1, high);
return node;
};