forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconstree.cpp
52 lines (40 loc) · 1.33 KB
/
constree.cpp
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
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
struct node * left, * right;
};
struct node * newNode(int data) {
struct node * node = (struct node * ) malloc(sizeof(struct node));
node -> data = data;
node -> left = NULL;
node -> right = NULL;
return (node);
}
node * constructTree(vector < int > & preorder, int preStart, int preEnd, vector
< int > & inorder, int inStart, int inEnd, map < int, int > & mp) {
if (preStart > preEnd || inStart > inEnd) return NULL;
node * root = newNode(preorder[preStart]);
int elem = mp[root -> data];
int nElem = elem - inStart;
root -> left = constructTree(preorder, preStart + 1, preStart + nElem, inorder,
inStart, elem - 1, mp);
root -> right = constructTree(preorder, preStart + nElem + 1, preEnd, inorder,
elem + 1, inEnd, mp);
return root;
}
node * buildTree(vector < int > & preorder, vector < int > & inorder) {
int preStart = 0, preEnd = preorder.size() - 1;
int inStart = 0, inEnd = inorder.size() - 1;
map < int, int > mp;
for (int i = inStart; i <= inEnd; i++) {
mp[inorder[i]] = i;
}
return constructTree(preorder, preStart, preEnd, inorder, inStart, inEnd, mp);
}
int main() {
vector<int> preorder{10,20,40,50,30,60};
vector<int> inorder{40,20,50,10,60,30};
node * root = buildTree(preorder, inorder);
return 0;
}