Open In App

Reverse zigzag Traversal of a Binary Tree

Last Updated : 11 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Binary Tree, the task is to print the Reverse zigzag Order of the tree.
Examples: 
 

Input:
     1
   /  \
  2    3
 / \    \
4   5    6
Output: 6 5 4 2 3 1

Input:
      5
     / \
    9   3
   /     \
  6       4
 / \
8   7
Output: 7 8 6 4 3 9 5

 

Approach: The idea is to traverse the tree in a Reverse Level Order manner but with a slight modification. We will use a variable flag and initially set it’s value to one. As we complete the reverse level order traversal of the tree, from right to left we will set the value of flag to zero, so that next time we traverse the Tree from left to right and as we complete the traversal we set it’s value back to one. We will repeat this whole step until we have traversed the Binary Tree completely.
Below is the implementation of the above approach: 
 

C++




// C++ program to print reverse
// zigzag order of binary tree
#include <bits/stdc++.h>
using namespace std;
 
// Binary tree node
struct node {
    struct node* left;
    struct node* right;
    int data;
};
 
// Function to create a new
// Binary node
struct node* newNode(int data)
{
    struct node* temp = new node;
 
    temp->data = data;
    temp->left = NULL;
    temp->right = NULL;
 
    return temp;
}
 
// Recursive Function to find height
// of binary tree
int HeightOfTree(struct node* root)
{
    if (root == NULL)
        return 0;
 
    // Compute the height of each subtree
    int lheight = HeightOfTree(root->left);
    int rheight = HeightOfTree(root->right);
 
    // Return the maximum of two
    return max(lheight + 1, rheight + 1);
}
 
// Function to Print nodes from right to left
void Print_Level_Right_To_Left(struct node* root, int level)
{
    if (root == NULL)
        return;
 
    if (level == 1)
        cout << root->data << " ";
 
    else if (level > 1) {
        Print_Level_Right_To_Left(root->right, level - 1);
        Print_Level_Right_To_Left(root->left, level - 1);
    }
}
 
// Function to Print nodes from left to right
void Print_Level_Left_To_Right(struct node* root, int level)
{
    if (root == NULL)
        return;
 
    if (level == 1)
        cout << root->data << " ";
 
    else if (level > 1) {
        Print_Level_Left_To_Right(root->left, level - 1);
        Print_Level_Left_To_Right(root->right, level - 1);
    }
}
 
// Function to print Reverse zigzag of
// a Binary tree
void PrintReverseZigZag(struct node* root)
{
    // Flag is used to mark the change
    // in level
    int flag = 1;
 
    // Height of tree
    int height = HeightOfTree(root);
 
    for (int i = height; i >= 1; i--) {
 
        // If flag value is one print nodes
        // from right to left
        if (flag == 1) {
            Print_Level_Right_To_Left(root, i);
 
            // Mark flag as zero so that next time
            // tree is traversed from left to right
            flag = 0;
        }
 
        // If flag is zero print nodes
        // from left to right
        else if (flag == 0) {
            Print_Level_Left_To_Right(root, i);
 
            // Mark flag as one so that next time
            // nodes are printed from right to left
            flag = 1;
        }
    }
}
 
// Driver code
int main()
{
    struct node* root = newNode(5);
    root->left = newNode(9);
    root->right = newNode(3);
    root->left->left = newNode(6);
    root->right->right = newNode(4);
    root->left->left->left = newNode(8);
    root->left->left->right = newNode(7);
 
    PrintReverseZigZag(root);
 
    return 0;
}


Java




// Java program to print reverse
// zigzag order of binary tree
class GfG
{
 
// Binary tree node
static class node
{
    node left;
    node right;
    int data;
}
 
// Function to create a new
// Binary node
static node newNode(int data)
{
    node temp = new node();
 
    temp.data = data;
    temp.left = null;
    temp.right = null;
 
    return temp;
}
 
// Recursive Function to find height
// of binary tree
static int HeightOfTree(node root)
{
    if (root == null)
        return 0;
 
    // Compute the height of each subtree
    int lheight = HeightOfTree(root.left);
    int rheight = HeightOfTree(root.right);
 
    // Return the maximum of two
    return Math.max(lheight + 1, rheight + 1);
}
 
// Function to Print nodes from right to left
static void Print_Level_Right_To_Left(node root, int level)
{
    if (root == null)
        return;
 
    if (level == 1)
        System.out.print(root.data + " ");
 
    else if (level > 1)
    {
        Print_Level_Right_To_Left(root.right, level - 1);
        Print_Level_Right_To_Left(root.left, level - 1);
    }
}
 
// Function to Print nodes from left to right
static void Print_Level_Left_To_Right(node root, int level)
{
    if (root == null)
        return;
 
    if (level == 1)
        System.out.print(root.data + " ");
 
    else if (level > 1)
    {
        Print_Level_Left_To_Right(root.left, level - 1);
        Print_Level_Left_To_Right(root.right, level - 1);
    }
}
 
// Function to print Reverse zigzag of
// a Binary tree
static void PrintReverseZigZag(node root)
{
    // Flag is used to mark the change
    // in level
    int flag = 1;
 
    // Height of tree
    int height = HeightOfTree(root);
 
    for (int i = height; i >= 1; i--)
    {
 
        // If flag value is one print nodes
        // from right to left
        if (flag == 1)
        {
            Print_Level_Right_To_Left(root, i);
 
            // Mark flag as zero so that next time
            // tree is traversed from left to right
            flag = 0;
        }
 
        // If flag is zero print nodes
        // from left to right
        else if (flag == 0)
        {
            Print_Level_Left_To_Right(root, i);
 
            // Mark flag as one so that next time
            // nodes are printed from right to left
            flag = 1;
        }
    }
}
 
// Driver code
public static void main(String[] args)
{
    node root = newNode(5);
    root.left = newNode(9);
    root.right = newNode(3);
    root.left.left = newNode(6);
    root.right.right = newNode(4);
    root.left.left.left = newNode(8);
    root.left.left.right = newNode(7);
 
    PrintReverseZigZag(root);
}
}
 
// This code is contributed by Prerna Saini.


Python3




# Python3 program to print reverse
# zigzag order of binary tree
 
# Binary tree node
class Node:
     
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
     
# Recursive Function to find
# height of binary tree
def HeightOfTree(root):
 
    if root == None:
        return 0
 
    # Compute the height of each subtree
    lheight = HeightOfTree(root.left)
    rheight = HeightOfTree(root.right)
 
    # Return the maximum of two
    return max(lheight + 1, rheight + 1)
 
# Function to Print nodes from right to left
def Print_Level_Right_To_Left(root, level):
 
    if root == None:
        return
 
    if level == 1:
        print(root.data, end = " ")
 
    elif level > 1:
        Print_Level_Right_To_Left(root.right,
                                  level - 1)
        Print_Level_Right_To_Left(root.left,
                                  level - 1)
 
# Function to Print nodes from left to right
def Print_Level_Left_To_Right(root, level):
 
    if root == None:
        return
 
    if level == 1:
        print(root.data, end = " ")
 
    elif level > 1:
        Print_Level_Left_To_Right(root.left,   
                                  level - 1)
        Print_Level_Left_To_Right(root.right,
                                  level - 1)
     
# Function to print Reverse
# zigzag of a Binary tree
def PrintReverseZigZag(root):
 
    # Flag is used to mark the
    # change in level
    flag = 1
 
    # Height of tree
    height = HeightOfTree(root)
 
    for i in range(height, 0, -1):
 
        # If flag value is one print
        # nodes from right to left
        if flag == 1:
            Print_Level_Right_To_Left(root, i)
 
            # Mark flag as zero so that next time
            # tree is traversed from left to right
            flag = 0
         
        # If flag is zero print nodes
        # from left to right
        elif flag == 0:
            Print_Level_Left_To_Right(root, i)
 
            # Mark flag as one so that next time
            # nodes are printed from right to left
            flag = 1
 
# Driver code
if __name__ == "__main__":
 
    root = Node(5)
    root.left = Node(9)
    root.right = Node(3)
    root.left.left = Node(6)
    root.right.right = Node(4)
    root.left.left.left = Node(8)
    root.left.left.right = Node(7)
 
    PrintReverseZigZag(root)
 
# This code is contributed by Rituraj Jain


C#




// C# program to print reverse
// zigzag order of binary tree
using System;
 
class GfG
{
 
// Binary tree node
public class node
{
    public node left;
    public node right;
    public int data;
}
 
// Function to create a new
// Binary node
static node newNode(int data)
{
    node temp = new node();
 
    temp.data = data;
    temp.left = null;
    temp.right = null;
 
    return temp;
}
 
// Recursive Function to find height
// of binary tree
static int HeightOfTree(node root)
{
    if (root == null)
        return 0;
 
    // Compute the height of each subtree
    int lheight = HeightOfTree(root.left);
    int rheight = HeightOfTree(root.right);
 
    // Return the maximum of two
    return Math.Max(lheight + 1, rheight + 1);
}
 
// Function to Print nodes from right to left
static void Print_Level_Right_To_Left(node root, int level)
{
    if (root == null)
        return;
 
    if (level == 1)
        Console.Write(root.data + " ");
 
    else if (level > 1)
    {
        Print_Level_Right_To_Left(root.right, level - 1);
        Print_Level_Right_To_Left(root.left, level - 1);
    }
}
 
// Function to Print nodes from left to right
static void Print_Level_Left_To_Right(node root, int level)
{
    if (root == null)
        return;
 
    if (level == 1)
        Console.Write(root.data + " ");
 
    else if (level > 1)
    {
        Print_Level_Left_To_Right(root.left, level - 1);
        Print_Level_Left_To_Right(root.right, level - 1);
    }
}
 
// Function to print Reverse zigzag of
// a Binary tree
static void PrintReverseZigZag(node root)
{
    // Flag is used to mark the change
    // in level
    int flag = 1;
 
    // Height of tree
    int height = HeightOfTree(root);
 
    for (int i = height; i >= 1; i--)
    {
 
        // If flag value is one print nodes
        // from right to left
        if (flag == 1)
        {
            Print_Level_Right_To_Left(root, i);
 
            // Mark flag as zero so that next time
            // tree is traversed from left to right
            flag = 0;
        }
 
        // If flag is zero print nodes
        // from left to right
        else if (flag == 0)
        {
            Print_Level_Left_To_Right(root, i);
 
            // Mark flag as one so that next time
            // nodes are printed from right to left
            flag = 1;
        }
    }
}
 
// Driver code
public static void Main(String[] args)
{
    node root = newNode(5);
    root.left = newNode(9);
    root.right = newNode(3);
    root.left.left = newNode(6);
    root.right.right = newNode(4);
    root.left.left.left = newNode(8);
    root.left.left.right = newNode(7);
 
    PrintReverseZigZag(root);
}
}
 
/* This code contributed by PrinciRaj1992 */


Javascript




<script>
 
    // JavaScript program to print reverse
    // zigzag order of binary tree
     
    // Binary tree node
    class node
    {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    }
     
    // Function to create a new
    // Binary node
    function newNode(data)
    {
        let temp = new node(data);
        return temp;
    }
 
    // Recursive Function to find height
    // of binary tree
    function HeightOfTree(root)
    {
        if (root == null)
            return 0;
 
        // Compute the height of each subtree
        let lheight = HeightOfTree(root.left);
        let rheight = HeightOfTree(root.right);
 
        // Return the maximum of two
        return Math.max(lheight + 1, rheight + 1);
    }
 
    // Function to Print nodes from right to left
    function Print_Level_Right_To_Left(root, level)
    {
        if (root == null)
            return;
 
        if (level == 1)
            document.write(root.data + " ");
 
        else if (level > 1)
        {
            Print_Level_Right_To_Left(root.right, level - 1);
            Print_Level_Right_To_Left(root.left, level - 1);
        }
    }
 
    // Function to Print nodes from left to right
    function Print_Level_Left_To_Right(root, level)
    {
        if (root == null)
            return;
 
        if (level == 1)
            document.write(root.data + " ");
 
        else if (level > 1)
        {
            Print_Level_Left_To_Right(root.left, level - 1);
            Print_Level_Left_To_Right(root.right, level - 1);
        }
    }
 
    // Function to print Reverse zigzag of
    // a Binary tree
    function PrintReverseZigZag(root)
    {
        // Flag is used to mark the change
        // in level
        let flag = 1;
 
        // Height of tree
        let height = HeightOfTree(root);
 
        for (let i = height; i >= 1; i--)
        {
 
            // If flag value is one print nodes
            // from right to left
            if (flag == 1)
            {
                Print_Level_Right_To_Left(root, i);
 
                // Mark flag as zero so that next time
                // tree is traversed from left to right
                flag = 0;
            }
 
            // If flag is zero print nodes
            // from left to right
            else if (flag == 0)
            {
                Print_Level_Left_To_Right(root, i);
 
                // Mark flag as one so that next time
                // nodes are printed from right to left
                flag = 1;
            }
        }
    }
     
    let root = newNode(5);
    root.left = newNode(9);
    root.right = newNode(3);
    root.left.left = newNode(6);
    root.right.right = newNode(4);
    root.left.left.left = newNode(8);
    root.left.left.right = newNode(7);
   
    PrintReverseZigZag(root);
 
</script>


Output: 

7 8 6 4 3 9 5

 

Time Complexity:O(N^2), where N is the number of nodes in a binary tree.
Auxiliary Space: O(N) 



Similar Reads

ZigZag Level Order Traversal of an N-ary Tree
Given a Generic Tree consisting of N nodes, the task is to find the ZigZag Level Order Traversal of the given tree. Examples: Input: Output:13 24 5 6 7 8 Approach: The given problem can be solved by using BFS Traversal. The approach is very similar to the Level Order Traversal of the N-ary Tree. It can be observed that on reversing the order of the
8 min read
ZigZag Tree Traversal
Write a function to print ZigZag order traversal of a binary tree. For the below binary tree the zigzag order traversal will be 1 3 2 7 6 5 4. Recommended PracticeZigZag Tree TraversalTry It!This problem can be solved using two stacks. Assume the two stacks are current: currentlevel and nextlevel. We would also need a variable to keep track of the
41 min read
Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, we need to write a program to construct the binary tree using these two Preorder traversals.A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a general binary tree using these two traver
12 min read
Level order traversal of Binary Tree using Morris Traversal
Given a binary tree, the task is to traverse the Binary Tree in level order fashion.Examples: Input: 1 / \ 2 3 Output: 1 2 3 Input: 5 / \ 2 3 \ 6 Output: 5 2 3 6 Approach: The idea is to use Morris Preorder Traversal to traverse the tree in level order traversal.Observations: There are mainly two observations for the traversal of the tree using Mor
11 min read
Pre Order, Post Order and In Order traversal of a Binary Tree in one traversal | (Using recursion)
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order in one iteration. Examples: Input: [caption width="800"] [/caption] Output: Pre Order: 1 2 4 5 3 6 7 Post Order: 4 5 2 6 7 3 1 In Order: 4 2 5 1 6 3 7 Input: [caption width="800"] [/caption] Output: Pre Order: 1 2 4 8 12 5 9 3 6 7 10 11
9 min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Reverse Morris traversal using Threaded Binary Tree
What is Morris traversal?Morris (InOrder) Traversal is a tree traversal algorithm that does not use recursion or stacks. This traversal creates links as descendants and outputs nodes using those links. Finally, undo the changes to restore the original tree.Given a binary tree, task is to do reverse inorder traversal using Morris Traversal. Prerequi
10 min read
Reverse Anti Clockwise Spiral Traversal of a Binary Tree
Given a binary tree, the task is to print the nodes of the tree in a reverse anti-clockwise spiral manner. Examples: Input : 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 Output : 7 8 9 1 4 5 6 3 2 Input : 20 / \ 8 22 / \ / \ 5 3 4 25 / \ 10 14 Output : 10 14 20 5 3 4 25 22 8 Approach: The idea is to use two variables i initialized to 1 and j initialized to th
11 min read
Reverse Clockwise spiral traversal of a binary tree
Given a Binary Tree. The task is to print the circular reverse clockwise spiral order traversal of the given binary tree.Reverse Clockwise Traversal means to traverse the tree in clockwise direction spirally starting from the bottom instead of top root node.Examples: Input : 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 Output : 9 8 7 1 6 5 4 2 3 Input : 20 /
11 min read
Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
Given the level order traversal of a Complete Binary Tree, determine whether the Binary Tree is a valid Min-Heap Examples: Input : level = [10, 15, 14, 25, 30] Output : True The tree of the given level order traversal is 10 / \ 15 14 / \ 25 30 We see that each parent has a value less than its child, and hence satisfies the min-heap property Input :
6 min read