forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0105.cpp
More file actions
executable file
·35 lines (28 loc) · 809 Bytes
/
LC0105.cpp
File metadata and controls
executable file
·35 lines (28 loc) · 809 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
/*
Problem Statement: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
Time: O(n)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int pos = 0, n = inorder.size();
unordered_map<int, int> mp;
// helper function
function<TreeNode*(int, int)> build = [&](int beg, int end) -> TreeNode* {
if (beg >= end)
return nullptr;
int mid = mp[preorder[pos]];
TreeNode* node = new TreeNode(preorder[pos]);
pos++;
node->left = build(beg, mid);
node->right = build(mid + 1, end);
return node;
};
// store position of elements in map
for (int i = 0; i < n; i++)
mp[inorder[i]] = i;
return build(0, n);
}
};