-
Notifications
You must be signed in to change notification settings - Fork 495
/
Copy pathMirrorOfGenricTree.cpp
128 lines (91 loc) Β· 1.95 KB
/
MirrorOfGenricTree.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
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <bits/stdc++.h>
using namespace std;
// https://www.geeksforgeeks.org/mirror-of-n-ary-tree/
class Node
{
public:
int data = 0;
vector<Node *> children;
Node(int data)
{
this->data = data;
}
};
void display(Node *node)
{
string s = "";
s += to_string(node->data) + " -> ";
for (Node *child : node->children)
{
s += to_string(child->data) + ", ";
}
cout << s << "." << endl;
for (Node *child : node->children)
{
display(child);
}
}
Node *constructor01(vector<int> &arr)
{
if (arr.size() == 0)
return NULL;
vector<Node *> stack;
stack.push_back(new Node(arr[0]));
Node *root = stack[0];
for (int i = 1; i < arr.size(); i++)
{
if (arr[i] != -1)
{
Node *node = stack.back();
Node *nnode = new Node(arr[i]);
node->children.push_back(nnode);
stack.push_back(nnode);
}
else
stack.pop_back();
}
return root;
}
void mirrorTransform(Node *node)
{
for (Node *child : node->children)
{
mirrorTransform(child);
}
// reverse(node->children);
for (int i = 0, j = node->children.size() - 1; i < j; i++, j--)
{
Node *temp = node->children[i];
node->children[i] = node->children[j];
node->children[j] = temp;
}
}
void solve()
{
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
// construct class for creating tree
Node *root = constructor01(arr);
// displaying Genric tree
cout << "Created Genric Tree";
cout << endl;
display(root);
cout << endl;
// class to find mirror of the genric tree
mirrorTransform(root);
// displaying mirror of the genric tree
cout << "Mirrored Genric Tree";
cout << endl;
display(root);
}
int main()
{
// solve class
solve();
return 0;
}