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

给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树。

高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。

示例 1:

输入:nums = [-10,-3,0,5,9]
输出:[0,-3,9,-10,null,5]
解释:[0,-10,5,null,-3,null,9] 也将被视为正确答案:

 

 示例 2:

 

 

 

输入:nums = [1,3]
输出:[3,1]
解释:[1,null,3] 和 [3,1] 都是高度平衡二叉搜索树。

提示:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums 按 严格递增 顺序排列
 1 /**
 2  * Defination for a binary tree node
 3  * function TreeNode(val,left,right){
 4  * this.val=(val===undefined?0:val)
 5  * this.left=(left===undefined?null:left)
 6  * this.right=(right===undefined?null:right)
 7  * }
 8  */
 9 /**
10  * @param {number[]} nums
11  * @return {TreeNode}
12  */
13 var sortedArrayToBST = function(nums) {
14     if (!nums.length) {
15         return null;
16     }
17     const headIndex = Math.floor(nums.length / 2);
18     const head = new TreeNode(nums[headIndex]);
19     let temp = head;
20     let left = headIndex - 1;
21     let right = headIndex + 1;
22     if (left >= 0) {
23         head.left = sortedArrayToBST(nums.slice(0, headIndex));
24     }
25     if (right < nums.length) {
26         head.right = sortedArrayToBST(nums.slice(right));
27     }
28     return head;
29 };

 

 

posted @ 2022-11-03 16:05  icyyyy  阅读(15)  评论(0)    收藏  举报