Skip to content

Instantly share code, notes, and snippets.

@yevmoroz
Created April 16, 2024 15:43
Show Gist options
  • Save yevmoroz/cd90920cf9c715cb0296e02283e4ff2e to your computer and use it in GitHub Desktop.
Save yevmoroz/cd90920cf9c715cb0296e02283e4ff2e to your computer and use it in GitHub Desktop.
leetcode sorted array to bst
/**
* 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}
*/
function sortedArrayToBST(nums, left = 0, right = nums.length - 1) {
if (left > right) {
return null;
}
const mid = Math.floor((left + right) / 2);
return new TreeNode(nums[mid], sortedArrayToBST(nums, left, mid - 1), sortedArrayToBST(nums, mid + 1, right));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment