leetcode

我的 leetcode 题解(JavaScript)


给一个有序数组, 构造一个二叉排序树

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {number[]} nums
 * @return {TreeNode}
 */
function sortedArrayToBST(num) {
  if (num.length == 0) {
    return null;
  }
  const head = helper(num, 0, num.length - 1);
  return head;
}

function helper(num, low, high) {
  if (low > high) {
    return null;
  }
  let mid = parseInt((low + high) / 2);
  const node = new TreeNode(num[mid]);
  node.left = helper(num, low, mid - 1);
  node.right = helper(num, mid + 1, high);
  return node;
}