Created
April 16, 2024 15:43
-
-
Save yevmoroz/cd90920cf9c715cb0296e02283e4ff2e to your computer and use it in GitHub Desktop.
leetcode sorted array to bst
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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