Given a binary tree and we have to find the spiral order traversal of the tree and return the list containing the elements. Spiral order Traversal:Â Starting from level 0 for root node, for all the even levels we print the node's value from right to left and for all the odd levels we print the node's value from left to right.
Example:
Input: root = [1, 2, 3, 7, 6, 5, 4]
Output: [1, 2, 3, 4, 5, 6, 7] Explanation: Start with root (1), print level 0 (right to left), level 1 (left to right), and continue alternating.
Input: root = [1, 3, 2]
Output: [1, 3, 2] Explanation: Start with root (1), print level 0 (right to left), then level 1 (left to right)
Input: root = [10, 20, 30, 40, 60]
Output: [10, 20, 30, 60, 40] Explanation: Start with root (10), print level 0 (right to left), level 1 (left to right), and continue alternating.
The idea is to first calculate the height of the tree, then recursively traverse each level and print the level order traversal according to the current level being odd or even.
Steps to solve the problem:
Find the height h of the binary tree.
Use a boolean flag variable ltr (left-to-right), start as false.
For each level ,Call printGivenLevel(root, level, ltr).
Toggle ltr after each level.
If node is null â return.
If level == 1 â process the current node.
If level > 1,If ltr â recurse left â right otherwise â recurse right â left.
C++
#include<iostream>#include<vector>usingnamespacestd;structNode{intdata;Node*left;Node*right;Node(intdata){this->data=data;left=right=nullptr;}};intheight(Node*node){if(node==nullptr)return0;intleftHeight=height(node->left);intrightHeight=height(node->right);returnmax(leftHeight,rightHeight)+1;}// Main recursive function that stores the// spiral traversal in vector res.voidgetLevel(Node*root,intlevel,boolltr,vector<int>&res){if(root==nullptr)return;if(level==1)res.push_back(root->data);elseif(level>1){if(ltr){getLevel(root->left,level-1,ltr,res);getLevel(root->right,level-1,ltr,res);}else{getLevel(root->right,level-1,ltr,res);getLevel(root->left,level-1,ltr,res);}}}vector<int>findSpiral(Node*root){vector<int>res;inth=height(root);boolltr=false;for(inti=1;i<=h;i++){getLevel(root,i,ltr,res);ltr=!ltr;}returnres;}voidprintSpiral(vector<int>&res){for(autoi:res)cout<<i<<" ";}intmain(){Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(7);root->left->right=newNode(6);root->right->left=newNode(5);root->right->right=newNode(4);vector<int>res=findSpiral(root);printSpiral(res);return0;}
Java
importjava.util.ArrayList;// Class representing a node of the binary treeclassNode{intdata;Nodeleft,right;Node(intdata){this.data=data;left=right=null;}}classGfG{// Function to calculate the height of the binary treestaticintheight(Nodenode){if(node==null)return0;intleftHeight=height(node.left);intrightHeight=height(node.right);// Height is max of left/right subtree + 1 (for current node)returnMath.max(leftHeight,rightHeight)+1;}// Function to perform spiral (zig-zag) level order traversalstaticArrayList<Integer>findSpiral(Noderoot){ArrayList<Integer>result=newArrayList<>();inth=height(root);// Get height of treebooleanleftToRight=false;// Direction flag// Traverse each levelfor(intlevel=1;level<=h;level++){getLevel(root,level,leftToRight,result);leftToRight=!leftToRight;}returnresult;}// Helper function to get nodes at a given level in desired orderstaticvoidgetLevel(Noderoot,intlevel,booleanleftToRight,ArrayList<Integer>result){if(root==null)return;if(level==1){// If it's the current level, add node to resultresult.add(root.data);}else{// Recur for left and right children in// order based on directionif(leftToRight){getLevel(root.left,level-1,leftToRight,result);getLevel(root.right,level-1,leftToRight,result);}else{getLevel(root.right,level-1,leftToRight,result);getLevel(root.left,level-1,leftToRight,result);}}}publicstaticvoidprintSpiral(ArrayList<Integer>res){for(intval:res)System.out.print(val+" ");}// Main function to test the spiral traversalpublicstaticvoidmain(String[]args){// Creating a binary treeNoderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(7);root.left.right=newNode(6);root.right.left=newNode(5);root.right.right=newNode(4);// Performing spiral traversalArrayList<Integer>res=findSpiral(root);// Printing the resultprintSpiral(res);}}
Python
#include <iostream>#include <vector>classNode:def__init__(self,data):self.data=dataself.left=Noneself.right=Nonedefheight(node):ifnodeisNone:return0leftHeight=height(node.left)rightHeight=height(node.right)returnmax(leftHeight,rightHeight)+1deffindSpiral(root):res=[]h=height(root)ltr=Falseforiinrange(1,h+1):getLevel(root,i,ltr,res)ltr=notltrreturnres# Main recursive function that stores the# spiral traversal in list res.defgetLevel(root,level,ltr,res):ifrootisNone:returniflevel==1:res.append(root.data)eliflevel>1:ifltr:getLevel(root.left,level-1,ltr,res)getLevel(root.right,level-1,ltr,res)else:getLevel(root.right,level-1,ltr,res)getLevel(root.left,level-1,ltr,res)defprintSpiral(res):forxinres:print(x,end=' ')if__name__=='__main__':root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(7)root.left.right=Node(6)root.right.left=Node(5)root.right.right=Node(4)res=findSpiral(root)printSpiral(res)
#include<iostream>#include<vector>#include<stack>usingnamespacestd;structNode{intdata;Node*left,*right;Node(intval){data=val;left=right=nullptr;}};vector<int>findSpiral(Node*root){vector<int>res;if(root==nullptr)returnres;stack<Node*>s1;// Current levelstack<Node*>s2;// Next levels1.push(root);while(!s1.empty()||!s2.empty()){// Print nodes of current level from s1// and push nodes of next level to s2while(!s1.empty()){Node*temp=s1.top();s1.pop();res.push_back(temp->data);if(temp->right)s2.push(temp->right);if(temp->left)s2.push(temp->left);}// Print nodes of current level from s2// and push nodes of next level to s1while(!s2.empty()){Node*temp=s2.top();s2.pop();res.push_back(temp->data);if(temp->left)s1.push(temp->left);if(temp->right)s1.push(temp->right);}}returnres;}// New function to print spiral order from result vectorvoidprintSpiral(vector<int>&res){for(intx:res)cout<<x<<" ";cout<<endl;}intmain(){Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(7);root->left->right=newNode(6);root->right->left=newNode(5);root->right->right=newNode(4);// First get resultvector<int>res=findSpiral(root);// Then pass it to printSpiralprintSpiral(res);return0;}
Java
importjava.util.*;classNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}publicclassSpiralTraversal{staticList<Integer>findSpiral(Noderoot){List<Integer>res=newArrayList<>();if(root==null)returnres;Stack<Node>s1=newStack<>();// Current levelStack<Node>s2=newStack<>();// Next levels1.push(root);while(!s1.isEmpty()||!s2.isEmpty()){// Print nodes of current level from s1// and push nodes of next level to s2while(!s1.isEmpty()){Nodetemp=s1.pop();res.add(temp.data);if(temp.right!=null)s2.push(temp.right);if(temp.left!=null)s2.push(temp.left);}// Print nodes of current level from s2// and push nodes of next level to s1while(!s2.isEmpty()){Nodetemp=s2.pop();res.add(temp.data);if(temp.left!=null)s1.push(temp.left);if(temp.right!=null)s1.push(temp.right);}}returnres;}// New function to print spiral order from result liststaticvoidprintSpiral(List<Integer>res){for(intx:res)System.out.print(x+" ");System.out.println();}publicstaticvoidmain(String[]args){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(7);root.left.right=newNode(6);root.right.left=newNode(5);root.right.right=newNode(4);// First get resultList<Integer>res=findSpiral(root);// Then pass it to printSpiralprintSpiral(res);}}
Python
classNode:def__init__(self,val):self.data=valself.left=Noneself.right=NonedeffindSpiral(root):res=[]ifrootisNone:returnress1=[]# Current levels2=[]# Next levels1.append(root)whiles1ors2:# Print nodes of current level from s1# and push nodes of next level to s2whiles1:temp=s1.pop()res.append(temp.data)iftemp.right:s2.append(temp.right)iftemp.left:s2.append(temp.left)# Print nodes of current level from s2# and push nodes of next level to s1whiles2:temp=s2.pop()res.append(temp.data)iftemp.left:s1.append(temp.left)iftemp.right:s1.append(temp.right)returnres# New function to print spiral order from result listdefprintSpiral(res):forxinres:print(x,end=" ")print()if__name__=="__main__":root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(7)root.left.right=Node(6)root.right.left=Node(5)root.right.right=Node(4)# First get resultres=findSpiral(root)# Then pass it to printSpiralprintSpiral(res)
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}classSpiralTraversal{staticList<int>findSpiral(Noderoot){List<int>res=newList<int>();if(root==null)returnres;Stack<Node>s1=newStack<Node>();// Current levelStack<Node>s2=newStack<Node>();// Next levels1.Push(root);while(s1.Count>0||s2.Count>0){// Print nodes of current level from s1// and push nodes of next level to s2while(s1.Count>0){Nodetemp=s1.Pop();res.Add(temp.data);if(temp.right!=null)s2.Push(temp.right);if(temp.left!=null)s2.Push(temp.left);}// Print nodes of current level from s2// and push nodes of next level to s1while(s2.Count>0){Nodetemp=s2.Pop();res.Add(temp.data);if(temp.left!=null)s1.Push(temp.left);if(temp.right!=null)s1.Push(temp.right);}}returnres;}// New function to print spiral order from result liststaticvoidprintSpiral(List<int>res){foreach(intxinres)Console.Write(x+" ");Console.WriteLine();}staticvoidMain(){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(7);root.left.right=newNode(6);root.right.left=newNode(5);root.right.right=newNode(4);// First get resultList<int>res=findSpiral(root);// Then pass it to printSpiralprintSpiral(res);}}
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functionfindSpiral(root){letres=[];if(root===null)returnres;lets1=[];// Current levellets2=[];// Next levels1.push(root);while(s1.length>0||s2.length>0){// Print nodes of current level from s1// and push nodes of next level to s2while(s1.length>0){lettemp=s1.pop();res.push(temp.data);if(temp.right)s2.push(temp.right);if(temp.left)s2.push(temp.left);}// Print nodes of current level from s2// and push nodes of next level to s1while(s2.length>0){lettemp=s2.pop();res.push(temp.data);if(temp.left)s1.push(temp.left);if(temp.right)s1.push(temp.right);}}returnres;}// New function to print spiral order from result arrayfunctionprintSpiral(res){console.log(res.join(" "));}letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(7);root.left.right=newNode(6);root.right.left=newNode(5);root.right.right=newNode(4);// First get resultletres=findSpiral(root);// Then pass it to printSpiralprintSpiral(res);
Output
1 2 3 4 5 6 7
Using Deque - O(n) Time and O(n) Space
The idea is to use Doubly Ended Queues, then push and pop the nodes from each end in alternate order.
Steps to solve the problem:
Start with a deque containing the root and a flag variable reverse = true.
While deque is not empty:
Process all nodes of the current level.
If reverse â pop from back, add children (right â left) at front.
Else â pop from front, add children (left â right) at back.
Flip reverse for each level.
C++
#include<iostream>#include<vector>#include<deque>usingnamespacestd;structNode{intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};vector<int>findSpiral(Node*root){vector<int>res;if(!root)returnres;deque<Node*>dq;dq.push_back(root);boolreverse=true;while(!dq.empty()){intn=dq.size();while(n--){// Push right first if reverse is trueif(reverse){Node*curr=dq.back();dq.pop_back();res.push_back(curr->data);if(curr->right)dq.push_front(curr->right);if(curr->left)dq.push_front(curr->left);}// Else push left firstelse{Node*curr=dq.front();dq.pop_front();res.push_back(curr->data);if(curr->left)dq.push_back(curr->left);if(curr->right)dq.push_back(curr->right);}}reverse=!reverse;}returnres;}// New function to print spiral order from result vectorvoidprintSpiral(vector<int>&res){for(intx:res)cout<<x<<" ";cout<<endl;}intmain(){Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(7);root->left->right=newNode(6);root->right->left=newNode(5);root->right->right=newNode(4);// First get resultvector<int>res=findSpiral(root);// Then pass it to printSpiralprintSpiral(res);return0;}
Java
importjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}publicclassSpiralTraversal{staticList<Integer>findSpiral(Noderoot){List<Integer>res=newArrayList<>();if(root==null)returnres;Deque<Node>dq=newLinkedList<>();dq.addLast(root);booleanreverse=true;while(!dq.isEmpty()){intn=dq.size();while(n-->0){// Push right first if reverse is trueif(reverse){Nodecurr=dq.removeLast();res.add(curr.data);if(curr.right!=null)dq.addFirst(curr.right);if(curr.left!=null)dq.addFirst(curr.left);}// Else push left firstelse{Nodecurr=dq.removeFirst();res.add(curr.data);if(curr.left!=null)dq.addLast(curr.left);if(curr.right!=null)dq.addLast(curr.right);}}reverse=!reverse;}returnres;}// New function to print spiral order from result liststaticvoidprintSpiral(List<Integer>res){for(intx:res)System.out.print(x+" ");System.out.println();}publicstaticvoidmain(String[]args){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(7);root.left.right=newNode(6);root.right.left=newNode(5);root.right.right=newNode(4);List<Integer>res=findSpiral(root);printSpiral(res);}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=NonedeffindSpiral(root):res=[]ifnotroot:returnresdq=deque()dq.append(root)reverse=Truewhiledq:n=len(dq)whilen>0:# Push right first if reverse is trueifreverse:curr=dq.pop()res.append(curr.data)ifcurr.right:dq.appendleft(curr.right)ifcurr.left:dq.appendleft(curr.left)# Else push left firstelse:curr=dq.popleft()res.append(curr.data)ifcurr.left:dq.append(curr.left)ifcurr.right:dq.append(curr.right)n-=1reverse=notreversereturnres# New function to print spiral order from result listdefprintSpiral(res):print(" ".join(map(str,res)))if__name__=="__main__":root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(7)root.left.right=Node(6)root.right.left=Node(5)root.right.right=Node(4)res=findSpiral(root)printSpiral(res)
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classSpiralTraversal{staticList<int>findSpiral(Noderoot){List<int>res=newList<int>();if(root==null)returnres;LinkedList<Node>dq=newLinkedList<Node>();dq.AddLast(root);boolreverse=true;while(dq.Count>0){intn=dq.Count;while(n-->0){// Push right first if reverse is trueif(reverse){Nodecurr=dq.Last.Value;dq.RemoveLast();res.Add(curr.data);if(curr.right!=null)dq.AddFirst(curr.right);if(curr.left!=null)dq.AddFirst(curr.left);}// Else push left firstelse{Nodecurr=dq.First.Value;dq.RemoveFirst();res.Add(curr.data);if(curr.left!=null)dq.AddLast(curr.left);if(curr.right!=null)dq.AddLast(curr.right);}}reverse=!reverse;}returnres;}// New function to print spiral order from result liststaticvoidprintSpiral(List<int>res){foreach(intxinres)Console.Write(x+" ");Console.WriteLine();}staticvoidMain(){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(7);root.left.right=newNode(6);root.right.left=newNode(5);root.right.right=newNode(4);List<int>res=findSpiral(root);printSpiral(res);}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}functionfindSpiral(root){letres=[];if(!root)returnres;letdq=[];dq.push(root);letreverse=true;while(dq.length>0){letn=dq.length;while(n-->0){// Push right first if reverse is trueif(reverse){letcurr=dq.pop();res.push(curr.data);if(curr.right)dq.unshift(curr.right);if(curr.left)dq.unshift(curr.left);}// Else push left firstelse{letcurr=dq.shift();res.push(curr.data);if(curr.left)dq.push(curr.left);if(curr.right)dq.push(curr.right);}}reverse=!reverse;}returnres;}// New function to print spiral order from result arrayfunctionprintSpiral(res){console.log(res.join(" "));}// Driver Codeletroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(7);root.left.right=newNode(6);root.right.left=newNode(5);root.right.right=newNode(4);letres=findSpiral(root);printSpiral(res);