leecode/backlog/108.convert-sorted-array-to-binary-search-tree.js

61 lines
1.6 KiB
JavaScript
Raw Normal View History

2020-05-22 18:17:19 +08:00
/*
* @lc app=leetcode id=108 lang=javascript
*
* [108] Convert Sorted Array to Binary Search Tree
*
* https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/
*
* algorithms
* Easy (49.37%)
* Total Accepted: 255.2K
* Total Submissions: 507.2K
* Testcase Example: '[-10,-3,0,5,9]'
*
* 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
*
*
*/
/**
* 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 = nums.length >> 1;
const root = new TreeNode(nums[mid]);
root.left = sortedArrayToBST(nums.slice(0, mid));
root.right = sortedArrayToBST(nums.slice(mid + 1))
return root;
// 扩展: 这道题启示我们如果是一个非排序的数组,我们可以先进行排序然后再按上述思路进行。
};