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++
#include <bits/stdc++.h>
using namespace std;
struct Node {
struct Node* left;
struct Node* right;
int data;
Node( int data)
{
this ->data = data;
this ->left = NULL;
this ->right = NULL;
}
};
int height( struct Node* root)
{
if (root == NULL)
return 0;
int lheight = height(root->left);
int rheight = height(root->right);
return max(lheight + 1, rheight + 1);
}
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);
}
}
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);
}
}
void reverseSpiral( struct Node* root)
{
int flag = 1;
int h = height(root);
for ( int i = h; i >= 1; i--) {
if (flag == 1) {
leftToRight(root, i);
flag = 0;
}
else if (flag == 0) {
rightToLeft(root, i);
flag = 1;
}
}
}
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;
}
|
Java
class Solution {
static class Node {
Node left;
Node right;
int data;
Node( int data)
{
this .data = data;
this .left = null ;
this .right = null ;
}
};
static int height(Node root)
{
if (root == null )
return 0 ;
int lheight = height(root.left);
int rheight = height(root.right);
return Math.max(lheight + 1 , rheight + 1 );
}
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 );
}
}
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 );
}
}
static void reverseSpiral(Node root)
{
int flag = 1 ;
int h = height(root);
for ( int i = h; i >= 1 ; i--) {
if (flag == 1 ) {
leftToRight(root, i);
flag = 0 ;
}
else if (flag == 0 ) {
rightToLeft(root, i);
flag = 1 ;
}
}
}
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);
}
}
|
Python3
class newNode:
def __init__( self , key):
self .data = key
self .left = None
self .right = None
def height(root):
if (root = = None ):
return 0
lheight = height(root.left)
rheight = height(root.right)
return max (lheight + 1 , rheight + 1 )
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 )
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 )
def reverseSpiral(root):
flag = 1
h = height(root)
for i in range (h, 0 , - 1 ):
if (flag = = 1 ):
leftToRight(root, i)
flag = 0
elif (flag = = 0 ):
rightToLeft(root, i)
flag = 1
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)
|
C#
using System;
class GFG {
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 ;
}
};
static int height(Node root)
{
if (root == null )
return 0;
int lheight = height(root.left);
int rheight = height(root.right);
return Math.Max(lheight + 1, rheight + 1);
}
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);
}
}
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);
}
}
static void reverseSpiral(Node root)
{
int flag = 1;
int h = height(root);
for ( int i = h; i >= 1; i--) {
if (flag == 1) {
leftToRight(root, i);
flag = 0;
}
else if (flag == 0) {
rightToLeft(root, i);
flag = 1;
}
}
}
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);
}
}
|
Javascript
<script>
class Node
{
constructor(data)
{
this .data = data;
this .left = null ;
this .right = null ;
}
}
function height(root)
{
if (root == null )
return 0;
let lheight = height(root.left);
let rheight = height(root.right);
return Math.max(lheight + 1, rheight + 1);
}
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 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 reverseSpiral(root)
{
let flag = 1;
let h = height(root);
for (let i = h; i >= 1; i--)
{
if (flag == 1)
{
leftToRight(root, i);
flag = 0;
}
else if (flag == 0)
{
rightToLeft(root, i);
flag = 1;
}
}
}
let 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);
</script>
|
Time Complexity Analysis : The best case time complexity of reverseSpiral() is O(n+n/2+n/4…) = O(n) in case of a perfect binary tree. And the worst case time complexity is O(n2) [O((n)+(n-1)+(n-2)+…] in case of a skewed tree taken as input.
Auxiliary Space: O(n) for call stack since using recursion.
Iterative Implementation –
The above problem can be solved with the help of queue and stack. Just perform a normal spiral traversal, use stack to use reverse the elements alternatively. Below is the implementation of the same –
C++14
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node( int val)
{
data = val;
left = right = NULL;
}
};
void reverseSpiral(Node* root)
{
if (root == NULL) {
return ;
}
queue<Node*> q;
stack< int > s;
bool reverse = true ;
q.push(root);
while (!q.empty()) {
int count = q.size();
for ( int i = 0; i < count; i++) {
Node* curr = q.front();
q.pop();
s.push(curr->data);
if (reverse) {
if (curr->right) {
q.push(curr->right);
}
if (curr->left) {
q.push(curr->left);
}
}
else {
if (curr->left) {
q.push(curr->left);
}
if (curr->right) {
q.push(curr->right);
}
}
}
reverse = !reverse;
}
while (!s.empty()) {
int curr = s.top();
cout << curr << " " ;
s.pop();
}
}
int main()
{
Node* root = new Node(5);
root->left = new Node(9);
root->right = new Node(3);
root->left->left = new Node(6);
root->left->right = new Node(4);
root->left->left->left = new Node(8);
root->left->left->right = new Node(7);
reverseSpiral(root);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static class Node {
int data;
Node left, right;
Node( int val)
{
this .data = val;
left = right = null ;
}
}
static void reverseSpiral(Node root)
{
if (root == null ) {
return ;
}
Queue<Node> q = new LinkedList<>();
Stack<Integer> s = new Stack<>();
boolean reverse = true ;
q.add(root);
while (!q.isEmpty()) {
int count = q.size();
for ( int i = 0 ; i < count; i++) {
Node curr = q.peek();
q.remove();
s.push(curr.data);
if (reverse) {
if (curr.right != null ) {
q.add(curr.right);
}
if (curr.left != null ) {
q.add(curr.left);
}
}
else {
if (curr.left != null ) {
q.add(curr.left);
}
if (curr.right != null ) {
q.add(curr.right);
}
}
}
reverse = !reverse;
}
while (!s.isEmpty()) {
int curr = s.peek();
System.out.print(curr + " " );
s.pop();
}
}
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.left.right = new Node( 4 );
root.left.left.left = new Node( 8 );
root.left.left.right = new Node( 7 );
reverseSpiral(root);
}
}
|
Python3
from collections import deque
class Node:
def __init__( self , x):
self .data = x
self .right = None
self .left = None
def reverseSpiral(root):
if (root = = None ):
return
q = deque()
s = []
reverse = True
q.append(root)
while ( len (q) > 0 ):
count = len (q)
for i in range (count):
curr = q.popleft()
s.append(curr.data)
if (reverse):
if (curr.right):
q.append(curr.right)
if (curr.left):
q.append(curr.left)
else :
if (curr.left):
q.append(curr.left)
if (curr.right):
q.append(curr.right)
reverse = not reverse
while ( len (s) > 0 ):
curr = s[ - 1 ]
print (curr, end = " " )
del s[ - 1 ]
if __name__ = = '__main__' :
root = Node( 5 )
root.left = Node( 9 )
root.right = Node( 3 )
root.left.left = Node( 6 )
root.left.right = Node( 4 )
root.left.left.left = Node( 8 )
root.left.left.right = Node( 7 )
reverseSpiral(root)
|
C#
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
class Node
{
public int data;
public Node left, right;
public Node( int val)
{
this .data = val;
left = right = null ;
}
}
static void ReverseSpiral(Node root)
{
if (root == null )
{
return ;
}
Queue<Node> q = new Queue<Node>();
Stack< int > s = new Stack< int >();
bool reverse = true ;
q.Enqueue(root);
while (q.Count > 0)
{
int count = q.Count;
for ( int i = 0; i < count; i++)
{
Node curr = q.Peek();
q.Dequeue();
s.Push(curr.data);
if (reverse)
{
if (curr.right != null )
{
q.Enqueue(curr.right);
}
if (curr.left != null )
{
q.Enqueue(curr.left);
}
}
else
{
if (curr.left != null )
{
q.Enqueue(curr.left);
}
if (curr.right != null )
{
q.Enqueue(curr.right);
}
}
}
reverse = !reverse;
}
while (s.Count > 0)
{
int curr = s.Peek();
Console.Write(curr + " " );
s.Pop();
}
}
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.left.right = new Node(4);
root.left.left.left = new Node(8);
root.left.left.right = new Node(7);
ReverseSpiral(root);
}
}
}
|
Javascript
<script>
class Node
{
constructor(data)
{
this .data = data;
this .left = this .right = null ;
}
}
function reverseSpiral(root)
{
if (root == null )
return
let q = [];
let s = [];
let reverse = true ;
q.push(root)
while ((q).length > 0)
{
let count = (q).length;
for (let i = 0; i < (count); i++)
{
curr = q.shift();
s.push(curr.data);
if (reverse)
{
if (curr.right)
q.push(curr.right);
if (curr.left)
q.push(curr.left);
}
else
{
if (curr.left)
q.push(curr.left);
if (curr.right)
q.push(curr.right);
}
}
reverse = !reverse
}
while ((s).length > 0)
{
curr = s.pop();
document.write(curr+ " " );
}
}
let root = new Node(5)
root.left = new Node(9)
root.right = new Node(3)
root.left.left = new Node(6)
root.left.right = new Node(4)
root.left.left.left = new Node(8)
root.left.left.right = new Node(7)
reverseSpiral(root)
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Improved by :HarendraSingh22
Last Updated :
12 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...