This commit is contained in:
yi-ge 2020-07-03 15:20:06 +08:00
parent 89d8ac5e58
commit 450f1f6b5d
3 changed files with 64 additions and 28 deletions

View File

@ -511,6 +511,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 105. 从前序与中序遍历序列构造二叉树 <https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/> - 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> - 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) - [合并 K 个排序链表](src/list/merge-k-sorted-lists.js)

View 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)
}

View File

@ -0,0 +1,5 @@
import { sortedArrayToBST } from '../../src/tree/convert-sorted-array-to-binary-search-tree.js'
test('将有序数组转换为二叉搜索树', () => {
expect(sortedArrayToBST()).toEqual()
})