ZigZag Tree Traversal in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a binary tree. Our task is to print the binary tree in a zigzag form.

Let’s take an example to understand the problem,

The zigzag traversal of the above binary tree is

3    5    1    8    7    0    4

To solve this problem, we need to traverse the binary tree level by level. The order of traversal will be flipped after each level.

Now, we will use two stacks(current and next) and one value for order. First, we will traverse the node from current and feed nodes from the left child to the right child so that reverse order will be returned. The again reverse from the current. The order variable plays a vital role in showing which side is to be printed.


Program to show the implementation of our solution,

 Live Demo

#include <iostream>
#include <stack>
using namespace std;
struct Node {
   int data;
   struct Node *left, *right;
void zigZagTreeTraversal(struct Node* root){
   if (!root)
   stack<struct Node*> currentlevel;
   stack<struct Node*> nextlevel;
   bool LtR = true;
   while (!currentlevel.empty()) {
      struct Node* temp = currentlevel.top();
      if (temp) {
         if (LtR) {
            if (temp->left)
            if (temp->right)
         else {
            if (temp->right)
            if (temp->left)
      if (currentlevel.empty()) {
         LtR = !LtR;
         swap(currentlevel, nextlevel);
struct Node* insertNode(int data){
   struct Node* node = new struct Node;
   node->data = data;
   node->left = node->right = NULL;
   return (node);
int main() {
   struct Node* root = insertNode(3);
   root->left = insertNode(1);
   root->right = insertNode(5);
   root->left->left = insertNode(8);
   root->left->right = insertNode(7);
   root->right->left = insertNode(0);
   root->right->right = insertNode(4);
   cout << "ZigZag traversal of the given binary tree is \n";
   return 0;


ZigZag traversal of the given binary tree is
3    5    1    8    7    0    4
Published on 17-Apr-2020 11:04:46