-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0889-construct-binary-tree-from-preorder-and-postorder-traversal.js
More file actions
67 lines (57 loc) · 1.96 KB
/
0889-construct-binary-tree-from-preorder-and-postorder-traversal.js
File metadata and controls
67 lines (57 loc) · 1.96 KB
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
/**
* Construct Binary Tree From Preorder And Postorder Traversal
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var constructFromPrePost = function (preorder, postorder) {
const preorderSize = preorder.length;
if (preorderSize === 0) {
return null;
}
const postorderValueToIndexMap = new Map();
for (
let currentPosition = 0;
currentPosition < preorderSize;
currentPosition++
) {
postorderValueToIndexMap.set(postorder[currentPosition], currentPosition);
}
const buildTreeRecursive = (
preorderTraversalStart,
preorderTraversalEnd,
postorderTraversalStart,
postorderTraversalEnd,
) => {
if (preorderTraversalStart >= preorderTraversalEnd) {
return null;
}
const currentLevelRootValue = preorder[preorderTraversalStart];
const currentLevelNode = new TreeNode(currentLevelRootValue);
if (preorderTraversalEnd - preorderTraversalStart === 1) {
return currentLevelNode;
}
const nextLeftSubtreeRootValue = preorder[preorderTraversalStart + 1];
const nextLeftSubtreeRootPostorderIndex = postorderValueToIndexMap.get(
nextLeftSubtreeRootValue,
);
const leftSubtreeElementsCount =
nextLeftSubtreeRootPostorderIndex - postorderTraversalStart + 1;
const constructedLeftChild = buildTreeRecursive(
preorderTraversalStart + 1,
preorderTraversalStart + 1 + leftSubtreeElementsCount,
postorderTraversalStart,
postorderTraversalStart + leftSubtreeElementsCount,
);
const constructedRightChild = buildTreeRecursive(
preorderTraversalStart + 1 + leftSubtreeElementsCount,
preorderTraversalEnd,
postorderTraversalStart + leftSubtreeElementsCount,
postorderTraversalEnd - 1,
);
currentLevelNode.left = constructedLeftChild;
currentLevelNode.right = constructedRightChild;
return currentLevelNode;
};
const finalRootNode = buildTreeRecursive(0, preorderSize, 0, preorderSize);
return finalRootNode;
};