Convert Sorted Array to Binary Search Tree
程序员文章站
2022-05-18 23:11:04
上面是将有序数组转为二叉树的代码~ 二分查找的速度为O(log n), 遍历二叉树的速度为O(n) ......
/** * 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) return null; const result = new treenode(nums) return result }; function treenode(nums) { if(nums.length){ const middleindex = math.floor(nums.length/2) this.val = nums[middleindex]; if(middleindex>0){ this.left = new treenode(nums.slice(0, middleindex)); } else { this.left = null } if(middleindex<nums.length-1){ this.right = new treenode(nums.slice(middleindex+1)); } else { this.right = null } } else { return null } }
上面是将有序数组转为二叉树的代码~
二分查找的速度为o(log n), 遍历二叉树的速度为o(n)
上一篇: ElasticSearch 评分排序
下一篇: 原生jQuery代码
推荐阅读
-
Convert Sorted Array to Binary Search Tree
-
【leetcode】-700. Search in a Binary Search Tree 查找二叉搜索树
-
LeetCode 33. Search in Rotated Sorted Array && 81. Search in Rotated Sorted Array II
-
Leetcode 33 Search in Rotated Sorted Array
-
LeetCode·33. Search in Rotated Sorted Array
-
leetcode 33. Search in Rotated Sorted Array
-
0033_Search in Rotated Sorted Array
-
Search in Rotated Sorted Array II
-
33. Search in Rotated Sorted Array
-
LeetCode------Search in Rotated Sorted Array