-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuildTree.cpp
More file actions
80 lines (63 loc) · 1.43 KB
/
BuildTree.cpp
File metadata and controls
80 lines (63 loc) · 1.43 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
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
#include <vector>
using namespace std;
// buildtree using preorder and inorder sequence
// Node class
class Node
{
public:
int data;
Node *left;
Node *right;
Node(int val)
{
data = val;
left = right = NULL;
}
};
// search root node
int search(vector<int> &inorder, int left, int right, int val)
{
for (int i = left; i <= right; i++)
{
if (inorder[i] == val)
{
return i;
}
}
return -1;
}
// helper function
Node *helper(vector<int> &preorder, vector<int> &inorder, int &preIdx, int left, int right)
{
// base case
if (left > right)
{
return NULL;
}
Node *root = new Node(preorder[preIdx]);
// inorder index
int inIdx = search(inorder, left, right, preorder[preIdx]);
preIdx++;
// left subtree call
root->left = helper(preorder, inorder, preIdx, left, inIdx - 1);
// right subtree call
root->right = helper(preorder, inorder, preIdx, inIdx + 1, right);
return root;
}
// buildtree
Node *buildTree(vector<int> &preorder, vector<int> &inorder)
{
// preoder index
int preIdx = 0;
return helper(preorder, inorder, preIdx, 0, inorder.size() - 1);
}
int main()
{
vector<int> preorder = {3, 9, 20, 15, 7};
vector<int> inorder = {9, 3, 15, 20, 7};
Node *root = buildTree(preorder, inorder);
// print root of tree
cout << root->data << endl;
return 0;
}