# 108. 将有序数组转换为二叉搜索树

function TreeNode(val, left, right) {
  this.val = val === undefined ? 0 : val
  this.left = left === undefined ? null : left
  this.right = right === undefined ? null : right
}

var sortedArrayToBST = function(nums) {
  return dfs(nums, 0, nums.length - 1)

  function dfs(nums, left, right) {
    if (left > right) return null

    const mid = Math.ceil((left + right) / 2)
    const root = new TreeNode(nums[mid])
    root.left = dfs(nums, left, mid - 1)
    root.right = dfs(nums, mid + 1, right)
    return root
  }
}

console.log(sortedArrayToBST([-10, -3, 0, 5, 9]))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Last Updated: 6/27/2023, 7:40:45 PM