-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC0889.cpp
More file actions
executable file
·36 lines (29 loc) · 814 Bytes
/
LC0889.cpp
File metadata and controls
executable file
·36 lines (29 loc) · 814 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/
Time: O(n)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
int pos = 0, n = post.size();
unordered_map<int, int> mp;
// helper function
function<TreeNode*(int)> build = [&](int prev) -> TreeNode* {
// base cases
if (pos == n || prev < mp[pre[pos]])
return nullptr;
prev = mp[pre[pos]];
TreeNode* node = new TreeNode(pre[pos]);
pos++;
node->left = build(prev);
node->right = build(prev);
return node;
};
// store position of elements in map
for (int i = 0; i < post.size(); i++)
mp[post[i]] = i;
return build(n);
}
};