-
Notifications
You must be signed in to change notification settings - Fork 0
/
tut114.c++
90 lines (76 loc) · 1.57 KB
/
tut114.c++
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
/*Create a mirror tree from the given binary tree -> Given a binary tree, the task is to create a new binary tree which is a mirror image of the given binary tree.
Examples:
Input:
5
/ \
3 6
/ \
2 4
Output:
Original tree: 2 3 4 5 6
Mirror tree will be:
5
/ \
6 3
/ \
4 2
Mirror tree: 6 5 4 3 2
*/
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *left;
Node *right;
};
Node *createNode(int data)
{
// Creating a node pointer
Node *temp;
// Allocating memory in the heap
temp = (struct Node *)malloc(sizeof(struct Node));
// Set the data
temp->data = data;
// Set the left and right children to NULL
temp->left = NULL;
temp->right = NULL;
// Finally return the created node
return temp;
}
void mirrorify(Node *root)
{
if (root == NULL)
{
return;
}
// Postorder traversal
mirrorify(root->left);
mirrorify(root->right);
swap(root->left, root->right);
}
// printing in inorder traversal
void printTree(Node *root)
{
if (root == NULL)
{
return;
}
printTree(root->left);
cout << root->data << " ";
printTree(root->right);
}
int main()
{
Node *root = createNode(5);
root->left = createNode(3);
root->right = createNode(6);
root->left->left = createNode(2);
root->left->right = createNode(4);
cout << "Original tree: ";
printTree(root);
mirrorify(root);
cout << "\nMirror tree: ";
printTree(root);
return 0;
}