-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCreate_Tree.cpp
More file actions
83 lines (72 loc) · 1.43 KB
/
Create_Tree.cpp
File metadata and controls
83 lines (72 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
81
82
83
/*
* @Date : 2020-04-10 16:13:25
* @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 printPreOrder(Node *root)
{
if (!root)
return;
cout << root->data << " ";
printPreOrder(root->left);
printPreOrder(root->right);
}
int main()
{
int t;
cin >> t;
while (t--)
{
int len;
cin >> len;
int inorder[len], postorder[len], k = len - 1;
for (int i = 0; i < len; i++)
cin >> inorder[i];
for (int i = 0; i < len; i++)
cin >> postorder[i];
Node *root = createBT(postorder, inorder, k, 0, len - 1);
printPreOrder(root);
}
return 0;
}