add: 将有序数组转换为二叉搜索树
This commit is contained in:
26
src/tree/convert-sorted-array-to-binary-search-tree.js
Normal file
26
src/tree/convert-sorted-array-to-binary-search-tree.js
Normal 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)
|
||||
}
|
Reference in New Issue
Block a user