forked from rathoresrikant/HacktoberFestContribute
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spiral order traversal of binary tree
120 lines (95 loc) · 2.44 KB
/
spiral order traversal of binary tree
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
//spiral order traversal of a binary tree
#include <bits/stdc++.h>
using namespace std;
// Data structure to store a Binary Tree node
struct Node
{
int key;
Node *left, *right;
};
// Function to create a new binary tree node having given key
Node* newNode(int key)
{
Node* node = new Node;
node->key = key;
node->left = node->right = nullptr;
return node;
}
// Function to insert given key into the tree
void insert(Node*& root, string level, int key)
{
// tree is empty
if (level.length() == 0)
{
root = newNode(key);
return;
}
int i = 0;
Node* ptr = root;
while (i < level.length() - 1)
{
if (level[i++] == 'L')
ptr = ptr->left;
else
ptr = ptr->right;
}
if (level[i] == 'L')
ptr->left = newNode(key);
else
ptr->right = newNode(key);
}
// Function to print all nodes of a given level from left to right
bool printLevelLeftToRight(Node* root, int level)
{
if (root == nullptr)
return false;
if (level == 1)
{
cout << root->key << " ";
return true;
}
// process left child before right child
bool left = printLevelLeftToRight(root->left, level - 1);
bool right = printLevelLeftToRight(root->right, level - 1);
return left || right;
}
// Function to print all nodes of a given level from right to left
bool printLevelRightToLeft(Node* root, int level)
{
if (root == nullptr)
return false;
if (level == 1)
{
cout << root->key << " ";
return true;
}
// process right child before left child
bool right = printLevelRightToLeft(root->right, level - 1);
bool left = printLevelRightToLeft(root->left, level - 1);
return right || left;
}
// Function to print level order traversal of given binary tree
void spiralOrderTraversal(Node* root)
{
if (root == nullptr)
return;
// start from level 1 -- till height of the tree
int level = 1;
// run till either function returns false
while (printLevelLeftToRight(root, level++) &&
printLevelRightToLeft(root, level++));
}
// main function
int main()
{
Node* root = nullptr;
vector<pair<string, int> > keys =
{
{"", 15}, {"L", 10}, {"R", 20}, {"LL", 8},
{"LR", 12}, {"RL", 16}, {"RR", 25}
};
for (auto pair: keys)
insert(root, pair.first, pair.second);
spiralOrderTraversal(root);
return 0;
}