forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverseLevelOrderTraversal.cpp
93 lines (80 loc) · 2.1 KB
/
reverseLevelOrderTraversal.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
/*
* Reverse Level Order Traversal of Binary Tree
* Given a binary tree, print its nodes level by level in reverse order.
* i.e. all nodes present at last level should be printed first followed
* by nodes of second-last level and so on..
* All nodes for any level should be printed from left to right.
*
* 1
* / \
* 2 3
* / \ / \
* 4 5 6 7
*
* The reverse level order traversal of the tree is :
* 4, 5, 6, 7, 2, 3, 1
*/
#include <iostream>
#include <stack>
#include <queue>
struct TreeNode
{
int data;
TreeNode *left;
TreeNode *right;
TreeNode (int d)
: data {d}
, left {nullptr}
, right {nullptr} {}
};
void printReverseLevelOrder(TreeNode* root)
{
if (!root)
{
return;
}
// Idea is to do a level order traversal and then
// push the nodes in a stack, so we can print in
// reverse order.
//
std::queue<TreeNode*> nodeQueue;
std::stack<TreeNode*> nodeStack;
nodeQueue.push(root);
while (!nodeQueue.empty())
{
TreeNode* curr = nodeQueue.front();
nodeQueue.pop();
nodeStack.push(curr);
// We will push right node first, as we want to print
// reverse level order traversal.
//
if (curr->right)
{
nodeQueue.push(curr->right);
}
if (curr->left)
{
nodeQueue.push(curr->left);
}
}
std::cout << "Reverse level order traversal:";
while (!nodeStack.empty())
{
TreeNode* curr = nodeStack.top();
std::cout << curr->data << " ";
nodeStack.pop();
}
std::cout << std::endl;
}
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);
printReverseLevelOrder(root);
return 0;
}