Reverse Level Order traversal in spiral form

Given a binary tree, the task is to print the reverse level order in spiral form.

Examples:

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

Input:
     5
   /   \
  6     4
 / \   / 
7   1 8
 \     \
  3     10
Output: 3 10 8 1 7 6 4 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 left to right we will set the value of flag to zero, so that next time we traverse the Tree from right to left 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to print reverse level order 
// traversal of a binary tree in spiral form
#include <bits/stdc++.h>
using namespace std;
  
// Binary tree Node
struct 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 tree
int height(struct Node* root)
{
    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(lheight + 1, rheight + 1);
}
  
// Function to Print Nodes from right to left
void 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 Nodes from left to right
void 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 Reverse level order traversal
// of a Binary tree in spiral form
void reverseSpiral(struct Node* root)
{
    // Flag is used to mark the change
    // in level
    int flag = 1;
  
    // Height of tree
    int h = height(root);
  
    for (int i = h; i >= 1; i--) {
  
        // If flag value is one print Nodes
        // from left to right
        if (flag == 1) {
            leftToRight(root, i);
  
            // Mark flag as zero so that next time
            // tree is traversed from right to left
            flag = 0;
        }
  
        // If flag is zero print Nodes
        // from right to left
        else if (flag == 0) {
            rightToLeft(root, i);
  
            // Mark flag as one so that next time
            // Nodes are printed from left to right
            flag = 1;
        }
    }
}
  
// Driver code
int main()
{
    struct Node* root = new Node(5);
    root->left = new Node(9);
    root->right = new Node(3);
    root->left->left = new Node(6);
    root->right->right = new Node(4);
    root->left->left->left = new Node(8);
    root->left->left->right = new Node(7);
  
    reverseSpiral(root);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to print reverse level order 
// traversal of a binary tree in spiral form
class Solution
{
      
// 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)
{
    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(lheight + 1, rheight + 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 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 Reverse level order traversal
// of a Binary tree in spiral form
static void reverseSpiral( Node root)
{
    // Flag is used to mark the change
    // in level
    int flag = 1;
  
    // Height of tree
    int h = height(root);
  
    for (int i = h; i >= 1; i--) 
    {
  
        // If flag value is one print Nodes
        // from left to right
        if (flag == 1
        {
            leftToRight(root, i);
  
            // Mark flag as zero so that next time
            // tree is traversed from right to left
            flag = 0;
        }
  
        // If flag is zero print Nodes
        // from right to left
        else if (flag == 0
        {
            rightToLeft(root, i);
  
            // Mark flag as one so that next time
            // Nodes are printed from left to right
            flag = 1;
        }
    }
}
  
// Driver code
public static void main(String args[])
{
    Node root = new Node(5);
    root.left = new Node(9);
    root.right = new Node(3);
    root.left.left = new Node(6);
    root.right.right = new Node(4);
    root.left.left.left = new Node(8);
    root.left.left.right = new Node(7);
  
    reverseSpiral(root);
}
}
  
// This code is contributed by Arnab Kundu

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to prreverse level order 
# traversal of a binary tree in spiral form
  
class newNode: 
  
    # Construct to create a newNode 
    def __init__(self, key): 
        self.data = key 
        self.left = None
        self.right = None
  
# Recursive Function to find height 
# of binary tree 
def height(root):
  
    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(lheight + 1, rheight + 1
  
# Function to PrNodes from right to left 
def 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 PrNodes from left to right
def 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 prReverse level order traversal 
# of a Binary tree in spiral form 
def reverseSpiral(root):
  
    # Flag is used to mark the 
    # change in level 
    flag = 1
  
    # Height of tree 
    h = height(root) 
  
    for i in range(h, 0, -1): 
  
        # If flag value is one prNodes 
        # from left to right 
        if (flag == 1):
            leftToRight(root, i) 
  
            # Mark flag as zero so that next time 
            # tree is traversed from right to left 
            flag = 0
          
        # If flag is zero prNodes 
        # from right to left 
        elif (flag == 0):
            rightToLeft(root, i) 
  
            # Mark flag as one so that next time 
            # Nodes are printed from left to right 
            flag = 1
      
# Driver Code
if __name__ == '__main__':
    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
  
    reverseSpiral(root) 
      
# This code is contributed 
# by SHUBHAMSINGH10

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to print reverse level order 
// traversal of a binary tree in spiral form 
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) 
    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(lheight + 1, rheight + 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 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 Reverse level order traversal 
// of a Binary tree in spiral form 
static void reverseSpiral( Node root) 
    // Flag is used to mark the change 
    // in level 
    int flag = 1; 
  
    // Height of tree 
    int h = height(root); 
  
    for (int i = h; i >= 1; i--) 
    
  
        // If flag value is one print Nodes 
        // from left to right 
        if (flag == 1) 
        
            leftToRight(root, i); 
  
            // Mark flag as zero so that next time 
            // tree is traversed from right to left 
            flag = 0; 
        
  
        // If flag is zero print Nodes 
        // from right to left 
        else if (flag == 0) 
        
            rightToLeft(root, i); 
  
            // Mark flag as one so that next time 
            // Nodes are printed from left to right 
            flag = 1; 
        
    
  
// Driver code 
public static void Main(String []args) 
    Node root = new Node(5); 
    root.left = new Node(9); 
    root.right = new Node(3); 
    root.left.left = new Node(6); 
    root.right.right = new Node(4); 
    root.left.left.left = new Node(8); 
    root.left.left.right = new Node(7); 
  
    reverseSpiral(root); 
  
/* This code is contributed by PrinciRaj1992 */

chevron_right


Output:

8 7 4 6 9 3 5


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.