backup
This commit is contained in:
parent
89d8ac5e58
commit
450f1f6b5d
@ -511,6 +511,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
|
||||
- LeetCode 105. 从前序与中序遍历序列构造二叉树 <https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/>
|
||||
- LintCode 73. 前序遍历和中序遍历树构造二叉树 <https://www.lintcode.com/problem/construct-binary-tree-from-preorder-and-inorder-traversal/description>
|
||||
|
||||
- [将有序数组转换为二叉搜索树](src/tree/convert-sorted-array-to-binary-search-tree.js)
|
||||
|
||||
- LeetCode 108. 将有序数组转换为二叉搜索树 <https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/>
|
||||
- LintCode 106. 有序链表转换为二叉搜索树 <https://www.lintcode.com/problem/convert-sorted-list-to-binary-search-tree/description>
|
||||
|
||||
## 链表
|
||||
|
||||
- [合并 K 个排序链表](src/list/merge-k-sorted-lists.js)
|
||||
|
26
src/tree/convert-sorted-array-to-binary-search-tree.js
Normal file
26
src/tree/convert-sorted-array-to-binary-search-tree.js
Normal file
@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Definition for a binary tree node.
|
||||
*/
|
||||
function TreeNode(val) {
|
||||
this.val = val
|
||||
this.left = this.right = null
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number[]} nums
|
||||
* @return {TreeNode}
|
||||
*/
|
||||
export const sortedArrayToBST = function (nums) {
|
||||
if (!nums.length) return null
|
||||
|
||||
const creatTree = (left, right) => {
|
||||
if (left > right) return null
|
||||
const mid = Math.floor((left + right) / 2)
|
||||
const root = new TreeNode(nums[mid])
|
||||
root.left = creatTree(left, mid - 1)
|
||||
root.right = creatTree(mid + 1, right)
|
||||
return root
|
||||
}
|
||||
|
||||
return creatTree(0, nums.length - 1)
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
import { sortedArrayToBST } from '../../src/tree/convert-sorted-array-to-binary-search-tree.js'
|
||||
|
||||
test('将有序数组转换为二叉搜索树', () => {
|
||||
expect(sortedArrayToBST()).toEqual()
|
||||
})
|
Loading…
Reference in New Issue
Block a user