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
/ \
8 22
/ \ / \
5 3 4 25
/ \
10 14
Output : 14 10 20 25 4 3 5 8 22
Approach: The idea is to use two variables i initialized to 1 and j initialized to the height of tree and run a while loop which wont break until i becomes greater than j.Â
- Use another variable flag and initialize it to 0. Now in the while loop, check a condition that if flag is equal to 0 then traverse the tree from right to left and mark flag as 1 so that next time we traverse the tree from left to right, this is done to maintain the spiral clockwise order of traversal.
- Then decrement the value of j so that next time the level just above the current level is visited.
- Also when we will traverse the level from top we will mark flag as 0 so that next time we traverse the tree from right to left and then increment the value of i so that next time we visit the level just below the current level.
- Repeat the whole process until the binary tree is completely traversed.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Binary tree nodestruct Node {Â Â Â Â struct Node* left;Â Â Â Â struct Node* right;Â Â Â Â int data;Â
    Node(int data)    {        this->data = data;        this->left = NULL;        this->right = NULL;    }};Â
// Recursive Function to find height// of binary treeint height(struct Node* root){    // Base condition    if (root == NULL)        return 0;Â
    // Compute the height of each subtree    int lheight = height(root->left);    int rheight = height(root->right);Â
    // Return the maximum of two    return max(1 + lheight, 1 + rheight);}Â
// Function to Print Nodes from left to rightvoid leftToRight(struct Node* root, int level){Â Â Â Â if (root == NULL)Â Â Â Â Â Â Â Â return;Â
    if (level == 1)        cout << root->data << " ";Â
    else if (level > 1) {        leftToRight(root->left, level - 1);        leftToRight(root->right, level - 1);    }}Â
// Function to Print Nodes from right to leftvoid rightToLeft(struct Node* root, int level){Â Â Â Â if (root == NULL)Â Â Â Â Â Â Â Â return;Â
    if (level == 1)        cout << root->data << " ";Â
    else if (level > 1) {        rightToLeft(root->right, level - 1);        rightToLeft(root->left, level - 1);    }}Â
// Function to print reverse clockwise spiral// traversal of a binary treevoid ReverseClockWiseSpiral(struct Node* root){Â Â Â Â int i = 1;Â Â Â Â int j = height(root);Â
    // Flag to mark a change in the direction    // of printing nodes    int flag = 0;    while (i <= j) {Â
        // If flag is zero print nodes        // from right to left        if (flag == 0) {            rightToLeft(root, j);Â
            // Set the value of flag as zero            // so that nodes are next time            // printed from left to right            flag = 1;Â
            // Decrement j            j--;        }Â
        // If flag is one print nodes        // from left to right        else {            leftToRight(root, i);Â
            // Set the value of flag as zero            // so that nodes are next time            // printed from right to left            flag = 0;Â
            // Increment i            i++;        }    }}Â
// Driver codeint main(){Â Â Â Â struct Node* root = new Node(1);Â Â Â Â root->left = new Node(2);Â Â Â Â root->right = new Node(3);Â Â Â Â root->left->left = new Node(4);Â Â Â Â root->right->left = new Node(6);Â Â Â Â root->right->right = new Node(7);Â Â Â Â root->left->right = new Node(5);Â
    ReverseClockWiseSpiral(root);Â
    return 0;} |
Java
// Java implementation of the approach import java.util.*;Â
class GFG{Â Â Â Â Â // Binary tree node static class Node { Â Â Â Â Node left; Â Â Â Â Node right; Â Â Â Â int data; Â
    Node(int data)     {         this.data = data;         this.left = null;         this.right = null;     } }; Â
// Recursive Function to find height // of binary tree static int height( Node root) {     // Base condition     if (root == null)         return 0; Â
    // Compute the height of each subtree     int lheight = height(root.left);     int rheight = height(root.right); Â
    // Return the maximum of two     return Math.max(1 + lheight, 1 + rheight); } Â
// Function to Print Nodes from left to right static void leftToRight( Node root, int level) { Â Â Â Â if (root == null) Â Â Â Â Â Â Â Â return; Â
    if (level == 1)         System.out.print( root.data + " "); Â
    else if (level > 1)    {         leftToRight(root.left, level - 1);         leftToRight(root.right, level - 1);     } } Â
// Function to Print Nodes from right to left static void rightToLeft( Node root, int level) { Â Â Â Â if (root == null) Â Â Â Â Â Â Â Â return; Â
    if (level == 1)         System.out.print( root.data + " "); Â
    else if (level > 1)     {         rightToLeft(root.right, level - 1);         rightToLeft(root.left, level - 1);     } } Â
// Function to print reverse clockwise spiral // traversal of a binary tree static void ReverseClockWiseSpiral( Node root) { Â Â Â Â int i = 1; Â Â Â Â int j = height(root); Â
    // Flag to mark a change in the direction     // of printing nodes     int flag = 0;     while (i <= j)     { Â
        // If flag is zero print nodes         // from right to left         if (flag == 0)        {             rightToLeft(root, j); Â
            // Set the value of flag as zero             // so that nodes are next time             // printed from left to right             flag = 1; Â
            // Decrement j             j--;         } Â
        // If flag is one print nodes         // from left to right         else        {             leftToRight(root, i); Â
            // Set the value of flag as zero             // so that nodes are next time             // printed from right to left             flag = 0; Â
            // Increment i             i++;         }     } } Â
// Driver code public static void main(String args[]) { Â Â Â Â Node root = new Node(1); Â Â Â Â root.left = new Node(2); Â Â Â Â root.right = new Node(3); Â Â Â Â root.left.left = new Node(4); Â Â Â Â root.right.left = new Node(6); Â Â Â Â root.right.right = new Node(7); Â Â Â Â root.left.right = new Node(5); Â
    ReverseClockWiseSpiral(root); }} Â
// This code is contributed by Arnab Kundu |
Python3
# Python3 implementation of the approach  # Binary tree nodeclass Node:         def __init__(self,data):                 self.left = None        self.right = None        self.data = data;         # Recursive Function to find height# of binary treedef height(root):Â
    # Base condition    if (root == None):        return 0;      # Compute the height of each subtree    lheight = height(root.left);    rheight = height(root.right);      # Return the maximum of two    return max(1 + lheight, 1 + rheight);Â
# Function to Print Nodes from# left to rightdef leftToRight(root, level):Â
    if (root == None):        return;      if (level == 1):        print(root.data, end = " ")      elif (level > 1):        leftToRight(root.left, level - 1);        leftToRight(root.right, level - 1);         # Function to Print Nodes# from right to leftdef rightToLeft(root, level):Â
    if (root == None):        return;      if (level == 1):        print(root.data, end = " ")      elif (level > 1):        rightToLeft(root.right, level - 1);        rightToLeft(root.left, level - 1);         # Function to print Reverse clockwise# spiral traversal of a binary treedef ReverseClockWiseSpiral(root):Â
    i = 1;    j = height(root);      # Flag to mark a change in the    # direction of printing nodes    flag = 0;         while (i <= j):          # If flag is zero print nodes        # from right to left        if (flag == 0):            rightToLeft(root, j);              # Set the value of flag as zero            # so that nodes are next time            # printed from left to right            flag = 1;              # Increment i            j -= 1;                 # If flag is one print nodes        # from left to right        else:            leftToRight(root, i);              # Set the value of flag as zero            # so that nodes are next time            # printed from right to left            flag = 0;              # Decrement j            i += 1;Â
# Driver codeif __name__=="__main__":Â Â Â Â Â Â Â Â Â root = Node(1);Â Â Â Â root.left = Node(2);Â Â Â Â root.right = Node(3);Â Â Â Â root.left.left = Node(4);Â Â Â Â root.right.left = Node(6);Â Â Â Â root.right.right = Node(7);Â Â Â Â root.left.right = Node(5);Â Â Â Â Â Â ReverseClockWiseSpiral(root);Â
# This code is contributed by rutvik_56 |
C#
// C# implementation of the approach using System;Â
class GFG{Â Â Â Â Â // Binary tree node public class Node { Â Â Â Â public Node left; Â Â Â Â public Node right; Â Â Â Â public int data; Â
    public Node(int data)     {         this.data = data;         this.left = null;         this.right = null;     } }; Â
// Recursive Function to find height // of binary tree static int height( Node root) {     // Base condition     if (root == null)         return 0; Â
    // Compute the height of each subtree     int lheight = height(root.left);     int rheight = height(root.right); Â
    // Return the maximum of two     return Math.Max(1 + lheight, 1 + rheight); } Â
// Function to Print Nodes from left to right static void leftToRight( Node root, int level) { Â Â Â Â if (root == null) Â Â Â Â Â Â Â Â return; Â
    if (level == 1)         Console.Write( root.data + " "); Â
    else if (level > 1)    {         leftToRight(root.left, level - 1);         leftToRight(root.right, level - 1);     } } Â
// Function to Print Nodes from right to left static void rightToLeft( Node root, int level) { Â Â Â Â if (root == null) Â Â Â Â Â Â Â Â return; Â
    if (level == 1)         Console.Write( root.data + " "); Â
    else if (level > 1)     {         rightToLeft(root.right, level - 1);         rightToLeft(root.left, level - 1);     } } Â
// Function to print reverse clockwise spiral // traversal of a binary tree static void ReverseClockWiseSpiral( Node root) { Â Â Â Â int i = 1; Â Â Â Â int j = height(root); Â
    // Flag to mark a change in the direction     // of printing nodes     int flag = 0;     while (i <= j)     { Â
        // If flag is zero print nodes         // from right to left         if (flag == 0)        {             rightToLeft(root, j); Â
            // Set the value of flag as zero             // so that nodes are next time             // printed from left to right             flag = 1; Â
            // Decrement j             j--;         } Â
        // If flag is one print nodes         // from left to right         else        {             leftToRight(root, i); Â
            // Set the value of flag as zero             // so that nodes are next time             // printed from right to left             flag = 0; Â
            // Increment i             i++;         }     } } Â
// Driver code public static void Main(String []args) { Â Â Â Â Node root = new Node(1); Â Â Â Â root.left = new Node(2); Â Â Â Â root.right = new Node(3); Â Â Â Â root.left.left = new Node(4); Â Â Â Â root.right.left = new Node(6); Â Â Â Â root.right.right = new Node(7); Â Â Â Â root.left.right = new Node(5); Â
    ReverseClockWiseSpiral(root); }}Â
// This code contributed by Rajput-Ji |
Javascript
<script>Â
    // JavaScript implementation of the approach         // Binary tree node    class Node    {        constructor(data) {           this.left = null;           this.right = null;           this.data = data;        }    }         // Recursive Function to find height    // of binary tree    function height(root)    {        // Base condition        if (root == null)            return 0;Â
        // Compute the height of each subtree        let lheight = height(root.left);        let rheight = height(root.right);Â
        // Return the maximum of two        return Math.max(1 + lheight, 1 + rheight);    }Â
    // Function to Print Nodes from left to right    function leftToRight(root, level)    {        if (root == null)            return;Â
        if (level == 1)            document.write( root.data + " ");Â
        else if (level > 1)        {            leftToRight(root.left, level - 1);            leftToRight(root.right, level - 1);        }    }Â
    // Function to Print Nodes from right to left    function rightToLeft(root, level)    {        if (root == null)            return;Â
        if (level == 1)            document.write( root.data + " ");Â
        else if (level > 1)        {            rightToLeft(root.right, level - 1);            rightToLeft(root.left, level - 1);        }    }Â
    // Function to print reverse clockwise spiral    // traversal of a binary tree    function ReverseClockWiseSpiral(root)    {        let i = 1;        let j = height(root);Â
        // Flag to mark a change in the direction        // of printing nodes        let flag = 0;        while (i <= j)        {Â
            // If flag is zero print nodes            // from right to left            if (flag == 0)            {                rightToLeft(root, j);Â
                // Set the value of flag as zero                // so that nodes are next time                // printed from left to right                flag = 1;Â
                // Decrement j                j--;            }Â
            // If flag is one print nodes            // from left to right            else            {                leftToRight(root, i);Â
                // Set the value of flag as zero                // so that nodes are next time                // printed from right to left                flag = 0;Â
                // Increment i                i++;            }        }    }         let root = new Node(1);    root.left = new Node(2);    root.right = new Node(3);    root.left.left = new Node(4);    root.right.left = new Node(6);    root.right.right = new Node(7);    root.left.right = new Node(5);      ReverseClockWiseSpiral(root);Â
</script> |
Output:Â
7 6 5 4 1 3 2
Â
Time Complexity: O(N^2), where N is the total number of nodes in the binary tree.Â
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



