-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathconstruct-tree-from-given-inorder-and-preorder-traversal.cpp
More file actions
58 lines (50 loc) · 1.25 KB
/
construct-tree-from-given-inorder-and-preorder-traversal.cpp
File metadata and controls
58 lines (50 loc) · 1.25 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
// https://www.geeksforgeeks.org/construct-tree-from-given-inorder-and-preorder-traversal/
#include <bits/stdc++.h>
using namespace std;
struct Node{
char data;
Node *left , *right;
};
Node *getNode(char data){
Node *temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
}
int search(int in[], int data, int l, int r){
for(int i=l ;i<=r; i++){
if(in[i] == data){
return i;
}
}
return -1;
}
Node *buildTree(int in[], int pre[], int inStart, int inEnd){
static int preIndex = 0;
if(inStart > inEnd)
return NULL;
Node *root = getNode(pre[preIndex]);
preIndex += 1;
if(inStart == inEnd)
return root;
int inIndex = search(in,root->data,inStart, inEnd);
if(inIndex == -1){
cout << "Error\n";
return NULL;
}
root->left = buildTree(in,pre,inStart,inIndex-1);
root->right = buildTree(in, pre, inIndex+1, inEnd);
return root;
}
void inorder(Node *root){
if(!root) return;
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
int main(){
int pre[] = {'A','B','D','E','C','F'};
int in[] = {'D','B','E','A','F','C'};
Node *root = buildTree(in,pre,0,5);
inorder(root);
return 0;
}