Skip to content

掌握 查找 插入 删除 三个基本操作

javascript

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

const sortedArrayToBST = function (nums) {
  const len = nums.length;
  if(!len) return null;

  const buildBST = (low, height) => {
    if(low > height) return null;
    const mid = Math.floor(low + (height - low) / 2);
    const cur = new TreeNode(nums[mid]);
    cur.left = buildBST(low, mid -1);
    cur.right = buildBST(mid +1, height);
    return cur;
  }

  const root = buildBST(0, len-1);

  return root;
};