This repository has been archived by the owner on Oct 23, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathmirror-tree.cpp
107 lines (97 loc) · 1.79 KB
/
mirror-tree.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
#include <iostream>
#include <queue>
using namespace std;
class BstNode {
public:
int data;
BstNode *left;
BstNode *right;
BstNode(int d) {
data = d;
left = NULL;
right = NULL;
}
};
class Tree {
public:
BstNode *root;
Tree() {
root = NULL;
}
void insert(int d) {
BstNode *newNode = new BstNode(d);
//cout<<newNode->data<<endl;
if(root == NULL) {
root = newNode;
return;
}
BstNode *temp = root;
int flag = 1;
while(flag) {
if(d > temp->data) {
if(temp->right != NULL)
temp = temp->right;
else {
temp->right = newNode;
flag = 0;
}
}
else if(d < temp->data) {
if(temp->left != NULL)
temp = temp->left;
else {
temp->left = newNode;
flag = 0;
}
}
else
flag = 0;
}
}
void levelTraversal() {
cout<<"Level Traversing"<<endl;
queue<BstNode*> lvl;
lvl.push(root);
while(!lvl.empty()) {
BstNode *temp = lvl.front();
lvl.pop();
if(temp->left != NULL)
lvl.push(temp->left);
if(temp->right != NULL)
lvl.push(temp->right);
cout<<temp->data<<endl;
}
}
};
void swap(BstNode *root) {
BstNode *temp = root->left;
root->left = root->right;
root->right = temp;
}
void mirrorTree(BstNode *root) {
queue<BstNode*> s;
s.push(root);
while(!s.empty()) {
BstNode *temp = s.front();
s.pop();
swap(temp);
if(temp->left != NULL)
s.push(temp->left);
if(temp->right != NULL)
s.push(temp->right);
}
}
int main() {
Tree t;
t.insert(9);
t.insert(12);
t.insert(7);
t.insert(13);
t.insert(11);
t.insert(5);
t.insert(4);
t.levelTraversal();
mirrorTree(t.root);
t.levelTraversal();
return 0;
}