add: 将有序数组转换为二叉搜索树

This commit is contained in:
2020-07-06 07:58:05 +08:00
parent 89d8ac5e58
commit 146b33a651
3 changed files with 64 additions and 28 deletions

View File

@ -0,0 +1,26 @@
/**
* Definition for a binary tree node.
*/
function TreeNode(val) {
this.val = val
this.left = this.right = null
}
/**
* @param {number[]} nums
* @return {TreeNode}
*/
export const sortedArrayToBST = function (nums) {
if (!nums.length) return null
const creatTree = (left, right) => {
if (left > right) return null
const mid = Math.floor((left + right) / 2)
const root = new TreeNode(nums[mid])
root.left = creatTree(left, mid - 1)
root.right = creatTree(mid + 1, right)
return root
}
return creatTree(0, nums.length - 1)
}