Skip to content

Commit 0252262

Browse files
authored
Create main.cpp
1 parent 4509a04 commit 0252262

File tree

1 file changed

+34
-0
lines changed
  • 17 - Binary Tree Data Structure Problems/30 - Construct Tree From In-Order & Pre-Order

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution{
2+
public:
3+
4+
void createMapping(int in[], map<int, int> &nodeToIndex, int n){
5+
for(int i = 0; i < n; i++){
6+
nodeToIndex[in[i]] = i;
7+
}
8+
9+
}
10+
11+
Node* solve(int in[], int pre[], int &index, int inOrderStart, int inOrderEnd, int n, map<int, int> &nodeToIndex){
12+
if(index >= n || inOrderStart > inOrderEnd) return NULL;
13+
14+
int element = pre[index++];
15+
Node* root = new Node(element);
16+
17+
int position = nodeToIndex[element];
18+
19+
root->left = solve(in, pre, index, inOrderStart, position - 1, n, nodeToIndex);
20+
root->right = solve(in, pre, index, position + 1, inOrderEnd, n, nodeToIndex);
21+
22+
return root;
23+
}
24+
25+
Node* buildTree(int in[],int pre[], int n)
26+
{
27+
int preOrderIndex = 0;
28+
map<int, int> nodeToIndex;
29+
createMapping(in, nodeToIndex, n);
30+
31+
return solve(in, pre, preOrderIndex, 0, n-1, n, nodeToIndex);
32+
33+
}
34+
};

0 commit comments

Comments
 (0)