-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path889.根据前序和后序遍历构造二叉树.js
80 lines (73 loc) · 1.88 KB
/
889.根据前序和后序遍历构造二叉树.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
* @lc app=leetcode.cn id=889 lang=javascript
*
* [889] 根据前序和后序遍历构造二叉树
*/
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {number[]} preorder
* @param {number[]} postorder
* @return {TreeNode}
*/
function TreeNode(val, left, right) {
this.val = val === undefined ? 0 : val
this.left = left === undefined ? null : left
this.right = right === undefined ? null : right
}
var constructFromPrePost = function(preorder, postorder) {
const memo = new Map()
for (let i = 0; i < postorder.length; i++) {
memo.set(postorder[i], i)
}
return build(
preorder,
0,
preorder.length - 1,
postorder,
0,
postorder.length - 1
)
// preorder: |(rootVal)|(leftRootVal)|..root.left...|(rightRootVal)|root.right|
// postorder: |..root.left...|(leftRootVal,idx)|..root.right..|(rightRootVal)|(rootVal)|
function build(preorder, preStart, preEnd, postorder, postStart, postEnd) {
if (preStart > preEnd) {
return null
}
// another base case
if (preStart == preEnd) {
return new TreeNode(preorder[preStart])
}
const rootVal = preorder[preStart]
const leftRootVal = preorder[preStart + 1]
const idx = memo.get(leftRootVal)
const leftSize = idx - postStart + 1 // key point
const rootNode = new TreeNode(rootVal)
rootNode.left = build(
preorder,
preStart + 1,
preStart + leftSize,
postorder,
postStart,
idx
)
rootNode.right = build(
preorder,
preStart + leftSize + 1,
preEnd,
postorder,
idx + 1,
postEnd - 1
)
return rootNode
}
}
// @lc code=end
module.exports = { constructFromPrePost }