Given a binary tree, the task is to find its reverse level order traversal. The idea is to print the last level first, then the second last level, and so on. Like Level order traversal, every level is printed from left to right.
[Naive Approach] Using Recursion - O(n^2) Time and O(h) Space:
The algorithm for reverse level order traversal involves printing nodes level by level, starting from the bottom-most level and moving up to the root. First, the height of the tree is determined, denoted as h. The traversal then begins from level h and proceeds upwards to level 1. In each iteration, printGivenLevel function is called to print nodes at the current level. It prints the node's data if the current level matches the required level. If not, the function recursively explores the left and right subtrees to find and print nodes at the required level.
C++
// A recursive C++ program to print// reverse level order traversal#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Function to find the height of// the tree.intheight(Node*node){if(node==nullptr)return0;intlheight=height(node->left);intrheight=height(node->right);returnmax(lheight,rheight)+1;}// Print nodes at a given levelvoidprintGivenLevel(Node*root,intnodeLevel,intreqLevel){if(root==nullptr)return;// if the required level is reached,// then print the node.if(nodeLevel==reqLevel)cout<<root->data<<" ";// else call function for left and// right subtree.elseif(nodeLevel<reqLevel){printGivenLevel(root->left,nodeLevel+1,reqLevel);printGivenLevel(root->right,nodeLevel+1,reqLevel);}}// Function to print reverse// level order traversal a treevoidreverseLevelOrder(Node*root){// find the height of the tree.inth=height(root);// Start printing from the lowest level.for(inti=h;i>=1;i--)printGivenLevel(root,1,i);}intmain(){// create hard coded tree// 1// / \ // 2 3// / \ // 4 5Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);reverseLevelOrder(root);return0;}
C
// A recursive C program to print// reverse level order traversal#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};// Function to find the height of the tree.intheight(structNode*node){if(node==NULL)return0;intlheight=height(node->left);intrheight=height(node->right);return(lheight>rheight?lheight:rheight)+1;}// Print nodes at a given levelvoidprintGivenLevel(structNode*root,intnodeLevel,intreqLevel){if(root==NULL)return;// if the required level is reached,// then print the node.if(nodeLevel==reqLevel)printf("%d ",root->data);// else call function for left and right subtree.elseif(nodeLevel<reqLevel){printGivenLevel(root->left,nodeLevel+1,reqLevel);printGivenLevel(root->right,nodeLevel+1,reqLevel);}}// Function to print REVERSE level order traversal of a treevoidreverseLevelOrder(structNode*root){// find the height of the tree.inth=height(root);// Start printing from the lowest level.for(inti=h;i>=1;i--)printGivenLevel(root,1,i);}structNode*createNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->left=NULL;node->right=NULL;returnnode;}intmain(){// create hard coded tree// 1// / \ // 2 3// / \ // 4 5structNode*root=createNode(1);root->left=createNode(2);root->right=createNode(3);root->left->left=createNode(4);root->left->right=createNode(5);reverseLevelOrder(root);return0;}
Java
// A recursive Java program to print// reverse level order traversalclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Function to find the height of the tree.staticintheight(Nodenode){if(node==null)return0;intlheight=height(node.left);intrheight=height(node.right);returnMath.max(lheight,rheight)+1;}// Print nodes at a given levelstaticvoidprintGivenLevel(Noderoot,intnodeLevel,intreqLevel){if(root==null)return;// if the required level is reached, print the node.if(nodeLevel==reqLevel)System.out.print(root.data+" ");// else call function for left and right subtree.elseif(nodeLevel<reqLevel){printGivenLevel(root.left,nodeLevel+1,reqLevel);printGivenLevel(root.right,nodeLevel+1,reqLevel);}}// Function to print REVERSE level order traversal of a treestaticvoidreverseLevelOrder(Noderoot){// find the height of the tree.inth=height(root);// Start printing from the lowest level.for(inti=h;i>=1;i--)printGivenLevel(root,1,i);}publicstaticvoidmain(String[]args){// create hard coded tree// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);reverseLevelOrder(root);}}
Python
# A recursive Python program to print# reverse level order traversalclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to find the height of the tree.defheight(node):ifnodeisNone:return0lheight=height(node.left)rheight=height(node.right)returnmax(lheight,rheight)+1# Print nodes at a given leveldefprint_given_level(root,node_level,req_level):ifrootisNone:return# if the required level is reached, print the node.ifnode_level==req_level:print(root.data,end=" ")# else call function for left and right subtree.elifnode_level<req_level:print_given_level(root.left,node_level+1,req_level)print_given_level(root.right,node_level+1,req_level)# Function to print REVERSE level order traversal of a treedefreverse_level_order(root):# find the height of the tree.h=height(root)# Start printing from the lowest level.foriinrange(h,0,-1):print_given_level(root,1,i)if__name__=="__main__":# create hard coded tree# 1# / \# 2 3# / \# 4 5root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)reverse_level_order(root)
C#
// A recursive C# program to print// reverse level order traversalusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to find the height of the tree.staticintheight(Nodenode){if(node==null)return0;intlheight=height(node.left);intrheight=height(node.right);returnMath.Max(lheight,rheight)+1;}// Print nodes at a given levelstaticvoidprintGivenLevel(Noderoot,intnodeLevel,intreqLevel){if(root==null)return;// if the required level is reached, print the node.if(nodeLevel==reqLevel)Console.Write(root.data+" ");// else call function for left and right subtree.elseif(nodeLevel<reqLevel){printGivenLevel(root.left,nodeLevel+1,reqLevel);printGivenLevel(root.right,nodeLevel+1,reqLevel);}}// Function to print REVERSE level order traversal of a treestaticvoidreverseLevelOrder(Noderoot){// find the height of the tree.inth=height(root);// Start printing from the lowest level.for(inti=h;i>=1;i--)printGivenLevel(root,1,i);}staticvoidMain(){// create hard coded tree// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);reverseLevelOrder(root);}}
JavaScript
// A recursive Javascript program to print// reverse level order traversalclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to find the height of the tree.functionheight(node){if(node===null)return0;letlheight=height(node.left);letrheight=height(node.right);returnMath.max(lheight,rheight)+1;}// Print nodes at a given levelfunctionprintGivenLevel(root,nodeLevel,reqLevel){if(root===null)return;// if the required level is reached, print the node.if(nodeLevel===reqLevel)console.log(root.data);// else call function for left and right subtree.elseif(nodeLevel<reqLevel){printGivenLevel(root.left,nodeLevel+1,reqLevel);printGivenLevel(root.right,nodeLevel+1,reqLevel);}}// Function to print REVERSE level order traversal of a treefunctionreverseLevelOrder(root){// find the height of the tree.leth=height(root);// Start printing from the lowest level.for(leti=h;i>=1;i--)printGivenLevel(root,1,i);}// create hard coded tree// 1// / \// 2 3// / \// 4 5letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);reverseLevelOrder(root);
Output
4 5 2 3 1
Time Complexity: O(n^2) Auxiliary Space: O(h), where h is the height of the tree.
[Expected Approach] Using Stack and Queue - O(n) Time and O(n) Space:
The approach for reverse level order traversal, using a stack and queue is conceptually similar to a standard level order traversal but with key modifications. Instead of printing each node as it is visited, the nodes are pushed onto a stack. Additionally, when enqueueing children nodes, the right child is enqueued before the left child. This ensures that when nodes are popped from the stack, they are printed in reverse level order.
Step by step implementation:
The idea is to use a stack to get the reverse level order.
Push the root node into a queue. While queue is not empty, perform steps 3,4.
Pop the front element of the queue. Instead of printing it (like in level order), push node's value into a stack. This way the elements present on upper levels will be printed later than elements on lower levels.
If the right child of current node exists, push it into queue before left child. This is because elements on the same level should be printed from left to right.
While stack is not empty, pop the top element and print it.
C++
// C++ program to print reverse level // order traversal using stack and queue#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Function to print REVERSE // level order traversal of a treevoidreverseLevelOrder(Node*root){stack<Node*>st;queue<Node*>q;q.push(root);while(!q.empty()){// Dequeue nodeNode*curr=q.front();q.pop();st.push(curr);// Enqueue right childif(curr->right)q.push(curr->right);// Enqueue left childif(curr->left)q.push(curr->left);}// Pop all items from stack one by one and print themwhile(!st.empty()){Node*curr=st.top();cout<<curr->data<<" ";st.pop();}}intmain(){// Create hard coded tree// 1// / \ // 2 3// / \ // 4 5 Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);reverseLevelOrder(root);return0;}
Java
// Java program to print reverse level // order traversal using stack and queueimportjava.util.LinkedList;importjava.util.Queue;importjava.util.Stack;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Function to print REVERSE level order traversal of a treestaticvoidreverseLevelOrder(Noderoot){Stack<Node>st=newStack<>();Queue<Node>q=newLinkedList<>();q.add(root);while(!q.isEmpty()){// Dequeue nodeNodecurr=q.poll();st.push(curr);// Enqueue right childif(curr.right!=null)q.add(curr.right);// Enqueue left childif(curr.left!=null)q.add(curr.left);}// Pop all items from stack one by one and print themwhile(!st.isEmpty()){Nodecurr=st.pop();System.out.print(curr.data+" ");}}publicstaticvoidmain(String[]args){// Create hard coded tree// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);reverseLevelOrder(root);}}
Python
# Python program to print reverse level # order traversal using stack and queuefromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to print REVERSE level order traversal of a treedefreverse_level_order(root):st=[]q=deque([root])whileq:# Dequeue nodecurr=q.popleft()st.append(curr)# Enqueue right childifcurr.right:q.append(curr.right)# Enqueue left childifcurr.left:q.append(curr.left)# Pop all items from stack one by one and print themwhilest:curr=st.pop()print(curr.data,end=" ")if__name__=="__main__":# Create hard coded tree# 1# / \# 2 3# / \# 4 5root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)reverse_level_order(root)
C#
// C# program to print reverse level // order traversal using stack and queueusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to print REVERSE level order traversal of a treestaticvoidReverseLevelOrder(Noderoot){Stack<Node>S=newStack<Node>();Queue<Node>Q=newQueue<Node>();Q.Enqueue(root);while(Q.Count>0){// Dequeue nodeNodecurr=Q.Dequeue();S.Push(curr);// Enqueue right childif(curr.right!=null)Q.Enqueue(curr.right);// Enqueue left childif(curr.left!=null)Q.Enqueue(curr.left);}// Pop all items from stack one by one and print themwhile(S.Count>0){Nodecurr=S.Pop();Console.Write(curr.data+" ");}}staticvoidMain(string[]args){// Create a hard coded tree// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);ReverseLevelOrder(root);}}
JavaScript
// Javascript program to print reverse level // order traversal using stack and queueclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to print REVERSE level order traversal of a treefunctionreverseLevelOrder(root){letS=[];letQ=[];Q.push(root);while(Q.length>0){// Dequeue nodeletcurr=Q.shift();S.push(curr);// Enqueue right childif(curr.right)Q.push(curr.right);// Enqueue left childif(curr.left)Q.push(curr.left);}// pop all items from stack one by one and print themwhile(S.length>0){letcurr=S.pop();console.log(curr.data);}}// create hard coded tree// 1// / \// 2 3// / \// 4 5letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);reverseLevelOrder(root);
Output
4 5 2 3 1
Time Complexity: O(n), where n is the number of nodes in the binary tree. Auxiliary Space: O(n)
[Alternate Approach] Using a hash map - O(n) Time and O(n) Space:
The approach to reverse level order traversal using a hash map involves storing nodes by their levels and then retrieving them in reverse order. To achieve this, a hash map is used where each level of the binary tree maps to a list of nodes at that level. During a pre-order traversal of the tree, nodes are added to the hash map based on their level, ensuring that nodes are processed from the leftmost node at each level first. If the current node is null, the function returns immediately. Otherwise, it adds the node to the list corresponding to its level in the hash map, then recursively processes the left and right children.
After completing the traversal, the height of the tree, denoted by the size of the hash map, determines the number of levels. The final step is to iterate over the hash map from the highest level down to level 1, printing nodes from each level to achieve the reverse level order traversal.
Below is the implementation of the above approach:
C++
//C++ program to print reverse level // order traversal using hashmap#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Recursive function to traverse the binary// tree and add nodes to the hashmapvoidaddNodesToMap(Node*node,intlevel,unordered_map<int,vector<int>>&map){if(node==nullptr)return;// Add the current node to the vector of// nodes at its level in the hashmapmap[level].push_back(node->data);// Recursively traverse the left and// right subtreesaddNodesToMap(node->left,level+1,map);addNodesToMap(node->right,level+1,map);}vector<int>reverseLevelOrder(Node*root){vector<int>result;// Create an unordered_map to store the// nodes at each level of the binary treeunordered_map<int,vector<int>>map;// Traverse the binary tree recursively and// add nodes to the hashmapaddNodesToMap(root,0,map);// Iterate over the hashmap in reverse order of the// levels and add nodes to the result vectorfor(intlevel=map.size()-1;level>=0;level--){vector<int>nodesAtLevel=map[level];for(inti=0;i<nodesAtLevel.size();i++){result.push_back(nodesAtLevel[i]);}}returnresult;}voidprintList(vector<int>v){for(inti=0;i<v.size();i++){cout<<v[i]<<" ";}cout<<endl;}intmain(){// create hard coded tree// 1// / \ // 2 3// / \ // 4 5 Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);vector<int>result=reverseLevelOrder(root);printList(result);return0;}
Java
// Java program to print reverse level // order traversal using hashmapimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Recursive function to traverse the binary// tree and add nodes to the hashmapstaticvoidaddNodesToMap(Nodenode,intlevel,Map<Integer,List<Integer>>map){if(node==null)return;map.putIfAbsent(level,newArrayList<>());map.get(level).add(node.data);// Recursively traverse the left and right subtreesaddNodesToMap(node.left,level+1,map);addNodesToMap(node.right,level+1,map);}staticList<Integer>reverseLevelOrder(Noderoot){ArrayList<Integer>result=newArrayList<>();// Create a HashMap to store the nodes // at each level of the binary treeMap<Integer,List<Integer>>map=newHashMap<>();// Traverse the binary tree recursively // and add nodes to the hashmapaddNodesToMap(root,0,map);// Iterate over the hashmap in reverse //order of the levels and add nodes // to the resultfor(intlevel=map.size()-1;level>=0;level--){result.addAll(map.get(level));}returnresult;}publicstaticvoidmain(String[]args){// create hard coded tree// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);List<Integer>result=reverseLevelOrder(root);result.forEach(node->System.out.print(node+" "));}}
Python
# Python program to print REVERSE level # order traversal using hashmapfromcollectionsimportdefaultdictclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Recursive function to traverse the binary tree# and add nodes to the hashmapdefadd_nodes_to_map(node,level,map):ifnodeisNone:returnmap[level].append(node.data)# Recursively traverse the left and right subtreesadd_nodes_to_map(node.left,level+1,map)add_nodes_to_map(node.right,level+1,map)defreverse_level_order(root):result=[]# Create a defaultdict to store the nodes # at each level of the binary treemap=defaultdict(list)# Traverse the binary tree recursively # and add nodes to the hashmapadd_nodes_to_map(root,0,map)# Iterate over the hashmap in reverse order of # the levels and add nodes to the resultforlevelinreversed(range(len(map))):result.extend(map[level])returnresultdefprint_list(lst):print(" ".join(map(str,lst)))if__name__=="__main__":# create hard coded tree# 1# / \# 2 3# / \# 4 5root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)result=reverse_level_order(root)print_list(result)
C#
// A C# program to print REVERSE level // order traversal using hashmapusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Recursive function to traverse the binary tree// and add nodes to the hashmapstaticvoidAddNodesToMap(Nodenode,intlevel,Dictionary<int,List<int>>map){if(node==null)return;if(!map.ContainsKey(level))map[level]=newList<int>();map[level].Add(node.data);// Recursively traverse the left and right subtreesAddNodesToMap(node.left,level+1,map);AddNodesToMap(node.right,level+1,map);}staticList<int>ReverseLevelOrder(Noderoot){List<int>result=newList<int>();// Create a Dictionary to store the // nodes at each level of the binary treeDictionary<int,List<int>>map=newDictionary<int,List<int>>();// Traverse the binary tree recursively // and add nodes to the hashmapAddNodesToMap(root,0,map);// Iterate over the hashmap in reverse order// of the levels and add nodes to the resultfor(intlevel=map.Count-1;level>=0;level--){result.AddRange(map[level]);}returnresult;}staticvoidPrintList(List<int>list){foreach(variteminlist){Console.Write(item+" ");}Console.WriteLine();}staticvoidMain(string[]args){// create hard coded tree// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);List<int>result=ReverseLevelOrder(root);PrintList(result);}}
JavaScript
// JavaScript program to print REVERSE level // order traversal using hashmapclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Recursive function to traverse the binary tree// and add nodes to the hashmapfunctionaddNodesToMap(node,level,map){if(node===null)return;if(!map.has(level))map.set(level,[]);map.get(level).push(node.data);// Recursively traverse the left and right subtreesaddNodesToMap(node.left,level+1,map);addNodesToMap(node.right,level+1,map);}functionreverseLevelOrder(root){constresult=[];constmap=newMap();// Traverse the binary tree recursively // and add nodes to the hashmapaddNodesToMap(root,0,map);// Iterate over the hashmap in reverse order // of the levels and add nodes to the resultfor(letlevel=map.size-1;level>=0;level--){result.push(...map.get(level));}returnresult;}functionprintList(list){console.log(list.join(" "));}constroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);constresult=reverseLevelOrder(root);printList(result);
Output
4 5 2 3 1
Time complexity: O(n), where n is the number of nodes in the binary tree. Auxiliary Space: O(n)