Skip to content

Commit 855dfbe

Browse files
Merge pull request #379 from ys13579/master
Update treetaversal.cpp
2 parents 4852054 + 86d7312 commit 855dfbe

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Tree Traversal/C++/treetaversal.cpp

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,53 @@ void printLevelOrder(Node *root)
9292
q.push(node->right);
9393
}
9494
}
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+
95142

96143
/* Driver program to test above functions*/
97144
int main()
@@ -113,6 +160,9 @@ int main()
113160

114161
cout << "Level Order traversal of binary tree is \n";
115162
printLevelOrder(root);
163+
164+
cout << "Level Order traversal in Spiral form of binary tree is \n";
165+
printLevelOrderSpiral(root);
116166

117167
return 0;
118168
}

0 commit comments

Comments
 (0)