add: 从前序与中序遍历序列构造二叉树
This commit is contained in:
parent
2120bcdecf
commit
bf6f71f55f
2
.vscode/settings.json
vendored
2
.vscode/settings.json
vendored
@ -11,6 +11,7 @@
|
||||
"defanging",
|
||||
"dvdf",
|
||||
"eleetminicoworoep",
|
||||
"inorder",
|
||||
"lcci",
|
||||
"lcof",
|
||||
"lcov",
|
||||
@ -20,6 +21,7 @@
|
||||
"mincost",
|
||||
"nums",
|
||||
"powx",
|
||||
"preorder",
|
||||
"pwwkew",
|
||||
"subarray",
|
||||
"subarrays",
|
||||
|
@ -406,6 +406,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
|
||||
- LeetCode 107. 二叉树的层次遍历 II <https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/>
|
||||
- LintCode 70. 二叉树的层次遍历 II <https://www.lintcode.com/problem/binary-tree-level-order-traversal-ii/description>
|
||||
|
||||
- [从前序与中序遍历序列构造二叉树](src/tree/construct-binary-tree-from-preorder-and-inorder-traversal.js)
|
||||
|
||||
- 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>
|
||||
|
||||
## 链表
|
||||
|
||||
- [合并K个排序链表](src/list/merge-k-sorted-lists.js)
|
||||
|
@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Definition for a binary tree node.
|
||||
*/
|
||||
function TreeNode (val) {
|
||||
this.val = val
|
||||
this.left = this.right = null
|
||||
}
|
||||
|
||||
// 前序遍历:根左右
|
||||
// 中序遍历:左根右
|
||||
|
||||
// 前序遍历知道根、中序遍历知道左边长度。
|
||||
|
||||
/**
|
||||
* @param {number[]} preorder
|
||||
* @param {number[]} inorder
|
||||
* @return {TreeNode}
|
||||
*/
|
||||
export const buildTree = function (preorder, inorder) {
|
||||
if (inorder.length === 0) return null
|
||||
const root = new TreeNode(preorder[0])
|
||||
const index = inorder.indexOf(preorder[0])
|
||||
root.left = buildTree(preorder.slice(1, index + 1), inorder.slice(0, index))
|
||||
root.right = buildTree(preorder.slice(index + 1), inorder.slice(index + 1))
|
||||
return root
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
import { buildTree } from '../../src/tree/construct-binary-tree-from-preorder-and-inorder-traversal'
|
||||
|
||||
test('从前序与中序遍历序列构造二叉树', () => {
|
||||
expect(buildTree([3, 9, 20, 15, 7], [9, 3, 15, 20, 7])).toEqual({ left: { left: null, right: null, val: 9 }, right: { left: { left: null, right: null, val: 15 }, right: { left: null, right: null, val: 7 }, val: 20 }, val: 3 })
|
||||
})
|
Loading…
Reference in New Issue
Block a user