108. Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

0
/ \
-3 9
/ /
-10 5

Analyze

递归解题, 题目中高度平衡即当前节点的左右子节点的深度不超过 1 要稍微理解下。

  • 当数组为奇数时比如 [0, 1, 2], 此时取中间数 1 为根节点, 0 和 2 分别为其左右子节点, 此时满足高度平衡的条件。
  • 当数组为偶数时比如 [0, 1], 此时取中间数 1 为根节点, 0 为其左右子节点, 此时满足高度平衡的条件。
/**
* 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) {
if (nums.length === 0) return null
const mid = Math.floor(nums.length / 2)
const result = new TreeNode(nums[mid])
const left = nums.slice(0, mid)
const right = nums.slice(mid + 1, nums.length)
result.left = sortedArrayToBST(left)
result.right = sortedArrayToBST(right)
return result
};
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}