Anti Clockwise spiral traversal of a binary tree
Last Updated :
22 Aug, 2022
Given a binary tree, the task is to print the nodes of the tree in an anti-clockwise spiral manner.
Examples:
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
Output: 1 4 5 6 7 3 2
Input:
1
/ \
2 3
/ / \
4 5 6
/ \ / / \
7 8 9 10 11
Output: 1 7 8 9 10 11 3 2 4 5 6
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. We will use another variable flag and initialize it to 0. Now in the while loop we will check a condition that if flag is equal to 0 we will traverse the tree from right to left and mark flag as 1 so that next time we traverse the tree from left to right and then increment the value of i so that next time we visit the level just below the current level. Also when we will traverse the level from bottom we will mark flag as 0 so that next time we traverse the tree from left to right and then decrement the value of j so that next time we visit the level just above 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 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)
{
// 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 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 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 anti clockwise spiral
// traversal of a binary tree
void antiClockWiseSpiral(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, i);
// Set the value of flag as zero
// so that nodes are next time
// printed from left to right
flag = 1;
// Increment i
i++;
}
// If flag is one print nodes
// from left to right
else {
leftToRight(root, j);
// Set the value of flag as zero
// so that nodes are next time
// printed from right to left
flag = 0;
// Decrement j
j--;
}
}
}
// Driver code
int 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(5);
root->right->right = new Node(7);
root->left->left->left = new Node(10);
root->left->left->right = new Node(11);
root->right->right->left = new Node(8);
antiClockWiseSpiral(root);
return 0;
}
Java
// Java implementation of the approach
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 anti clockwise spiral
// traversal of a binary tree
static void antiClockWiseSpiral(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, i);
// Set the value of flag as zero
// so that nodes are next time
// printed from left to right
flag = 1;
// Increment i
i++;
}
// If flag is one print nodes
// from left to right
else {
leftToRight(root, j);
// Set the value of flag as zero
// so that nodes are next time
// printed from right to left
flag = 0;
// Decrement j
j--;
}
}
}
// 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(5);
root.right.right = new Node(7);
root.left.left.left = new Node(10);
root.left.left.right = new Node(11);
root.right.right.left = new Node(8);
antiClockWiseSpiral(root);
}
}
// This code is contributed by Prerna Saini.
Python3
# Python3 implementation of the approach
# Binary tree node
class newNode:
# Constructor to create a newNode
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.visited = False
# Recursive Function to find height
# of binary tree
def 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 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 Print Nodes 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 print anti clockwise spiral
# traversal of a binary tree
def antiClockWiseSpiral(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, i)
# Set the value of flag as zero
# so that nodes are next time
# printed from left to right
flag = 1
# Increment i
i += 1
# If flag is one print nodes
# from left to right
else:
leftToRight(root, j)
# Set the value of flag as zero
# so that nodes are next time
# printed from right to left
flag = 0
# Decrement j
j-=1
# Driver Code
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.right.left = newNode(5)
root.right.right = newNode(7)
root.left.left.left = newNode(10)
root.left.left.right = newNode(11)
root.right.right.left = newNode(8)
antiClockWiseSpiral(root)
# This code is contributed by
# SHUBHAMSINGH10
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 anti clockwise spiral
// traversal of a binary tree
static void antiClockWiseSpiral( 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, i);
// Set the value of flag as zero
// so that nodes are next time
// printed from left to right
flag = 1;
// Increment i
i++;
}
// If flag is one print nodes
// from left to right
else
{
leftToRight(root, j);
// Set the value of flag as zero
// so that nodes are next time
// printed from right to left
flag = 0;
// Decrement j
j--;
}
}
}
// 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(5);
root.right.right = new Node(7);
root.left.left.left = new Node(10);
root.left.left.right = new Node(11);
root.right.right.left = new Node(8);
antiClockWiseSpiral(root);
}
}
//This code is contributed by Arnab Kundu
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 anti clockwise spiral
// traversal of a binary tree
function antiClockWiseSpiral(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, i);
// Set the value of flag as zero
// so that nodes are next time
// printed from left to right
flag = 1;
// Increment i
i++;
}
// If flag is one print nodes
// from left to right
else {
leftToRight(root, j);
// Set the value of flag as zero
// so that nodes are next time
// printed from right to left
flag = 0;
// Decrement j
j--;
}
}
}
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(5);
root.right.right = new Node(7);
root.left.left.left = new Node(10);
root.left.left.right = new Node(11);
root.right.right.left = new Node(8);
antiClockWiseSpiral(root);
</script>
Output:
1 10 11 8 3 2 4 5 7
Another Approach:
The above approach have O(n^2) worst case complexity due to calling the print level everytime. An improvement over it can be storing the level wise nodes and use it to print.
C++
// C++ implementation of the above approach
#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;
}
};
void antiClockWiseSpiral(struct Node* root)
{
// Initialize the queue
queue<Node*> q;
// Add the root node
q.push(root);
// Initialize the vector
vector<Node*> topone;
// Until queue is not empty
while (!q.empty()) {
int len = q.size();
// len is greater than zero
while (len > 0) {
Node* nd = q.front();
q.pop();
if (nd != NULL) {
topone.push_back(nd);
if (nd->right != NULL)
q.push(nd->right);
if (nd->left != NULL)
q.push(nd->left);
}
len--;
}
topone.push_back(NULL);
}
bool top = true;
int l = 0, r = (int)topone.size() - 2;
while (l < r) {
if (top) {
while (l < (int)topone.size()) {
Node* nd = topone[l++];
if (nd == NULL) {
break;
}
cout << nd->data << " ";
}
}
else {
while (r >= l) {
Node* nd = topone[r--];
if (nd == NULL)
break;
cout << nd->data << " ";
}
}
top = !top;
}
}
// Build Tree
int main()
{
/*
1
2 3
4 5 7
10 11 8
*/
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(5);
root->right->right = new Node(7);
root->left->left->left = new Node(10);
root->left->left->right = new Node(11);
root->right->right->left = new Node(8);
antiClockWiseSpiral(root);
return 0;
}
Java
// Java implementation of the above approach
import java.io.*;
import java.util.*;
class GFG {
// Structure of each node
class Node {
int val;
Node left, right;
Node(int val)
{
this.val = val;
this.left = this.right = null;
}
}
private void work(Node root)
{
// Initialize queue
Queue<Node> q = new LinkedList<>();
// Add the root node
q.add(root);
// Initialize the vector
Vector<Node> topone = new Vector<>();
// Until queue is not empty
while (!q.isEmpty()) {
int len = q.size();
// len is greater than zero
while (len > 0) {
Node nd = q.poll();
if (nd != null) {
topone.add(nd);
if (nd.right != null)
q.add(nd.right);
if (nd.left != null)
q.add(nd.left);
}
len--;
}
topone.add(null);
}
boolean top = true;
int l = 0, r = topone.size() - 2;
while (l < r) {
if (top) {
while (l < topone.size()) {
Node nd = topone.get(l++);
if (nd == null) {
break;
}
System.out.print(nd.val + " ");
}
}
else {
while (r >= l) {
Node nd = topone.get(r--);
if (nd == null)
break;
System.out.print(nd.val + " ");
}
}
top = !top;
}
}
// Build Tree
public void solve()
{
/*
1
2 3
4 5 7
10 11 8
*/
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(5);
root.right.right = new Node(7);
root.left.left.left = new Node(10);
root.left.left.right = new Node(11);
root.right.right.left = new Node(8);
// Function call
work(root);
}
// Driver Code
public static void main(String[] args)
{
GFG t = new GFG();
t.solve();
}
}
Python3
# Python 3 implementation of the above approach
from collections import deque as dq
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def antiClockWiseSpiral(root):
# Initialize the queue
q=dq([root])
# Initialize the list
topone=[]
# Until queue is not empty
while (q):
l = len(q)
# l is greater than zero
while (l > 0):
nd = q.popleft()
if (nd != None):
topone.append(nd)
if (nd.right != None):
q.append(nd.right)
if (nd.left != None):
q.append(nd.left)
l-=1
topone.append(None)
top = True
l = 0; r = len(topone) - 2
while (l < r):
if (top):
while (l < len(topone)):
nd = topone[l]
l+=1
if (nd == None):
break
print(nd.data,end=" ")
else:
while (r >= l):
nd = topone[r]
r-=1
if (nd == None):
break
print(nd.data,end=" ")
top = not top
print()
# Build Tree
if __name__ == '__main__':
# 1
# 2 3
# 4 5 7
# 10 11 8
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.right.left = Node(5)
root.right.right = Node(7)
root.left.left.left = Node(10)
root.left.left.right = Node(11)
root.right.right.left = Node(8)
antiClockWiseSpiral(root)
C#
// C# implementation of the above approach
using System;
using System.Collections;
using System.Collections.Generic;
public class GFG {
// Structure of each node
class Node {
public int val;
public Node left, right;
public Node(int val)
{
this.val = val;
this.left = this.right = null;
}
}
private void work(Node root)
{
// Initialize queue
Queue q = new Queue();
// Add the root node
q.Enqueue(root);
// Initialize the vector
List<Node> topone = new List<Node>();
// Until queue is not empty
while (q.Count != 0) {
int len = q.Count;
// len is greater than zero
while (len > 0) {
Node nd = (Node)q.Dequeue();
if (nd != null) {
topone.Add(nd);
if (nd.right != null)
q.Enqueue(nd.right);
if (nd.left != null)
q.Enqueue(nd.left);
}
len--;
}
topone.Add(null);
}
bool top = true;
int l = 0, r = topone.Count - 2;
while (l < r) {
if (top) {
while (l < topone.Count) {
Node nd = topone[l++];
if (nd == null) {
break;
}
Console.Write(nd.val + " ");
}
}
else {
while (r >= l) {
Node nd = topone[r--];
if (nd == null)
break;
Console.Write(nd.val + " ");
}
}
top = !top;
}
}
// Build Tree
public void solve()
{
/*
1
2 3
4 5 7
10 11 8
*/
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(5);
root.right.right = new Node(7);
root.left.left.left = new Node(10);
root.left.left.right = new Node(11);
root.right.right.left = new Node(8);
// Function call
work(root);
}
static public void Main()
{
// Code
GFG t = new GFG();
t.solve();
}
}
// This code is contributed by lokeshmvs21.
JavaScript
<script>
// JavaScript code to implement the above approach
class Node {
constructor(data){
this.data = data;
this.left = null,this.right = null;
}
}
function antiClockWiseSpiral(root){
// Initialize the queue
let q = [root]
// Initialize the list
let topone=[]
// Until queue is not empty
while (q.length>0){
let l = q.length
// l is greater than zero
while (l > 0){
let nd = q.shift()
if (nd != null){
topone.push(nd)
if (nd.right != null)
q.push(nd.right)
if (nd.left != null)
q.push(nd.left)
}
l-=1
}
topone.push(null)
}
let top = true
let l = 0,r = topone.length - 2
while (l < r){
if (top){
while (l < topone.length){
let nd = topone[l]
l+=1
if (nd == null)
break
document.write(nd.data," ")
}
}
else{
while (r >= l){
let nd = topone[r]
r-=1
if (nd == null)
break
document.write(nd.data," ")
}
}
top = top^1
}
document.write("</br>")
}
// driver code
// Build Tree
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(5)
root.right.right = new Node(7)
root.left.left.left = new Node(10)
root.left.left.right = new Node(11)
root.right.right.left = new Node(8)
antiClockWiseSpiral(root)
// code is contributed by shinjanpatra
</script>
Output:
1 10 11 8 3 2 4 5 7
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem