-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path105. Construct Binary Tree from Preorder and Inorder Traversal.cpp
More file actions
67 lines (34 loc) · 1.28 KB
/
105. Construct Binary Tree from Preorder and Inorder Traversal.cpp
File metadata and controls
67 lines (34 loc) · 1.28 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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
// Recursive Approach might give Heap Buffer Overflow Error
class Solution {
public:
unordered_map<int, int> mp;
TreeNode* constructTree(vector<int> &preorder, vector<int> &inorder, int start, int end){
static int pIndex=0;
if(start>end) return NULL;
TreeNode* tNode= new TreeNode(preorder[pIndex++]);
if(start==end) return tNode;
int index=mp[tNode->val];
tNode->left=constructTree(preorder, inorder, start, index-1);
tNode->right=constructTree(preorder, inorder, index+1, end);
return tNode;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n=inorder.size();
// Storing data in map for O(1) searching
for(int i=0;i<n;i++)
mp[inorder[i]]=i;
return constructTree(preorder, inorder, 0, n-1); // <preorder, inorder, start, end>
}
};
// Follow Up-----> iterative Approach