File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change @@ -92,6 +92,53 @@ void printLevelOrder(Node *root)
92
92
q.push (node->right );
93
93
}
94
94
}
95
+
96
+ /* Given a binary tree, print its nodes in Levelorder in spiral form*/
97
+ void printLevelOrderSpiral (Node *root)
98
+ {
99
+ // Base Case
100
+ if (root == NULL ) return ;
101
+
102
+ // Create two empty stacks
103
+ stack<Node *> s1;
104
+ stack<Node *> s2;
105
+
106
+ // Push Root in s1
107
+ s1.add (root);
108
+
109
+ while (!s1.empty () || !s2.empty ())
110
+ {
111
+ // Print nodes of current level from s1 and push nodes of next level to s2
112
+ while (!s1.empty ()) {
113
+ Node *node = s1.top ();
114
+ s1.pop ();
115
+ cout << node->data << " " ;
116
+
117
+ // Node that is right is pushed before left
118
+ if (temp->right )
119
+ s2.push (temp->right );
120
+ if (temp->left )
121
+ s2.push (temp->left );
122
+
123
+ }
124
+
125
+ // Print nodes of current level from s2 and push nodes of next level to s1
126
+ while (!s2.empty ()) {
127
+ Node *node = s2.top ();
128
+ s2.pop ();
129
+ cout << node->data << " " ;
130
+
131
+ // Node that is right is pushed before left
132
+ if (temp->right )
133
+ s1.push (temp->right );
134
+ if (temp->left )
135
+ s1.push (temp->left );
136
+
137
+ }
138
+ }
139
+ }
140
+
141
+
95
142
96
143
/* Driver program to test above functions*/
97
144
int main ()
@@ -113,6 +160,9 @@ int main()
113
160
114
161
cout << " Level Order traversal of binary tree is \n " ;
115
162
printLevelOrder (root);
163
+
164
+ cout << " Level Order traversal in Spiral form of binary tree is \n " ;
165
+ printLevelOrderSpiral (root);
116
166
117
167
return 0 ;
118
168
}
You can’t perform that action at this time.
0 commit comments