-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution2.js
30 lines (30 loc) · 894 Bytes
/
solution2.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 106. 从中序与后序遍历序列构造二叉树
*
* https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
*
* Medium
*
* 左 根 右
*
* 左 右 根
*
* 100ms 94.87%
* 36.4mb 71.43%
*/
const buildTree = (inorder, postorder) => {
const record = new Map()
inorder.forEach((item, index) => record.set(item, index))
return _buildTree(inorder, postorder, 0, inorder.length - 1, 0, inorder.length - 1, record)
}
function _buildTree(inorder, postorder, sx, ex, sy, ey, record) {
if (sx > ex) {
return null
}
const rootValue = postorder[ey]
const root = new TreeNode(rootValue)
const index = record.get(rootValue)
root.left = _buildTree(inorder, postorder, sx, index - 1, sy, sy + index - sx - 1, record)
root.right = _buildTree(inorder, postorder, index + 1, ex, sy + index - sx, ey - 1, record)
return root
}