-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCreate_Tree_(Using_Postorder_and_Inorder).cpp
More file actions
88 lines (76 loc) · 1.54 KB
/
Create_Tree_(Using_Postorder_and_Inorder).cpp
File metadata and controls
88 lines (76 loc) · 1.54 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
81
82
83
84
85
86
87
88
/*
* @Date : 2020-04-10 16:31:46
* @Author : Abhimanyu Kumar Maurya (aerma7309@gmail.com)
* @Link : fb.com/aerma7309
*/
#include <iostream>
using namespace std;
bool ib = ios_base::sync_with_stdio(0);
bool it = cin.tie(0);
class Node
{
public:
int data;
Node *left;
Node *right;
public:
Node(int n);
~Node();
};
Node::Node(int n)
{
data = n;
left = nullptr;
right = nullptr;
}
Node::~Node()
{
}
Node *createBT(int post[], int in[], int &k, int start, int end)
{
if (start > end)
return nullptr;
int index = -1;
for (int i = end; i >= start; i--)
{
if (in[i] == post[k])
{
index = i;
break;
}
}
Node *root = new Node(post[k--]);
root->right = createBT(post, in, k, index + 1, end);
root->left = createBT(post, in, k, start, index - 1);
return root;
}
void printBT(const Node *root)
{
if (!root)
return;
if (!root->left)
cout << "END ";
else
cout << root->left->data << " ";
cout << "=> " << root->data << " <= ";
if (!root->right)
cout << "END\n";
else
cout << root->right->data << "\n";
printBT(root->left);
printBT(root->right);
}
int main()
{
int len;
cin >> len;
int inorder[len], postorder[len], k = len - 1;
for (int i = 0; i < len; i++)
cin >> postorder[i];
cin >> len;
for (int i = 0; i < len; i++)
cin >> inorder[i];
Node *root = createBT(postorder, inorder, k, 0, len - 1);
printBT(root);
return 0;
}