forked from Silver-Taurus/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
invert_a_tree.cpp
119 lines (108 loc) · 2.74 KB
/
invert_a_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
108
109
110
111
112
113
114
115
116
117
118
119
/*
* Invert given Binary Tree | Recursive and Iterative solution
* 1 1
* / \ / \
* 2 3 -> 3 2
* / \ / \ / \ / \
* 4 5 6 7 7 6 5 4
*
*/
#include <iostream>
#include <queue>
#include <iomanip>
struct TreeNode
{
int data;
TreeNode *left;
TreeNode *right;
TreeNode(int d)
: data{d}, left{nullptr}, right{nullptr} {}
};
void invertTreeRecur(TreeNode* root)
{
if (!root)
{
return;
}
// Swap left and right trees
//
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
// Do this recursively for left and right sub-trees.
//
invertTreeRecur(root->left);
invertTreeRecur(root->right);
}
void invertTreeIter(TreeNode* root)
{
if (!root)
{
return;
}
std::queue<TreeNode*> nodeQueue;
nodeQueue.push(root);
while(!nodeQueue.empty())
{
TreeNode* curr = nodeQueue.front();
nodeQueue.pop();
// Swap left and right children
//
TreeNode* temp = curr->left;
curr->left = curr->right;
curr->right = temp;
if (curr->left)
{
nodeQueue.push(curr->left);
}
if (curr->right)
{
nodeQueue.push(curr->right);
}
}
}
// Prints post order traversal of tree, where level expands left to right.
//
void postOrder(TreeNode* root, int indent = 0)
{
if (root)
{
if(root->right)
{
postOrder(root->right, indent+4);
}
if (indent) {
std::cout << std::setw(indent) << ' ';
}
if (root->right)
{
std::cout<<" /\n" << std::setw(indent) << ' ';
}
std::cout<< root->data << "\n ";
if(root->left)
{
std::cout << std::setw(indent) << ' ' <<" \\\n";
postOrder(root->left, indent + 4);
}
}
}
int main()
{
TreeNode *root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
std::cout << "Current Tree: \n";
postOrder(root);
std::cout << "\nInverting it recursively:\n";
invertTreeRecur(root);
postOrder(root);
std::cout << "\nInverting it again iteratively:\n";
invertTreeIter(root);
postOrder(root);
std::cout << std::endl;
return 0;
}