code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

108 Convert Sorted Array To Binary Search Tree

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

function TreeNode(val) {
  this.val = val
  this.left = this.right = null
}

const convertSortedArrayToBinarySearchTree = treeArray => {
  const buildTree = (treeArray, left, right) => {
    if (left > right) {
      return null
    }
    const mid = Math.floor(left + (right - left) / 2)
    const root = new TreeNode(treeArray[mid])
    root.left = buildTree(treeArray, left, mid - 1)
    root.right = buildTree(treeArray, mid + 1, right)
    return root
  }
  const tree = buildTree(treeArray, 0, treeArray.length - 1)
  return tree
}

console.log(convertSortedArrayToBinarySearchTree([-10, -3, 0, 5, 9]))

Created 2020-12-08T23:52:37+05:30, updated 2020-12-09T01:39:28+05:30 · History · Edit