108. 将有序数组转换为二叉搜索树(JS实现)

1 题目

将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定有序数组: [-10,-3,0,5,9],
一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
0
/
-3 9
/ /
-10 5

2 思路

这道题的主要思路是首先找到数组的中点,中点极为根节点,然后中点两侧的子数组就为左右子树,随后利用继续对左右两边进行划分,递归进行

3代码

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {number[]} nums
 * @return {TreeNode}
 */
var sortedArrayToBST = function(nums) {
  function d(arr, low, high) {
    if (low > high) return null;
    let mid = Math.floor((low + high) / 2);
    let node = new TreeNode(arr[mid]);

    node.left = d(arr, low, mid - 1);
    node.right = d(arr, mid+1, high);

    return node;
  }

  if (nums.length === 0) return null;
  return d(nums, 0, nums.length - 1);

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

猜你喜欢

转载自blog.csdn.net/zjw_python/article/details/107029224