前端嘛 Logo
前端嘛

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

题目链接

题目大意

用给定的有序数组生成一棵平衡二叉搜索树(平衡二叉树是指该树所有节点的左右子树的深度相差不超过 1。)

思路与代码

分治算法

  1. 找到数组的中间位置,用中间位置将数组分为左右两个子数组

  2. 中间位置作为根节点,其左右子树分别用两个子数组生成平衡二叉搜索树

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} nums
 * @return {TreeNode}
 */
var sortedArrayToBST = function (nums) {
  const to = (left, right) => {
    if (left > right) return null;
    const mid = Math.floor(left + (right - left) / 2);
    return new TreeNode(nums[mid], to(left, mid - 1), to(mid + 1, right));
  };

  return to(0, nums.length - 1);
};
  • 空间复杂度:O(log n) n 为数组长度

  • 时间复杂度:O(n) n 为数组长度