[Naive Approach] Level Order Traversal + Reverse Levels - O(n) Time and O(n) Space
The idea is to perform normal level order traversal using a queue and store the traversal in a vector. Once the complete level order traversal is obtained, simply reverse the vector to get the reverse level order traversal.
If the tree is empty, return an empty result.
Use a queue to perform level order traversal of the binary tree.
For each level, store all its node values in a separate list.
Store all the levels in a 2D list.
Traverse the levels from bottom to top and append their elements to the result.
Return the final result as the reverse level order traversal.
C++
#include<bits/stdc++.h>usingnamespacestd;/* Structure of Tree Node */classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};vector<int>reverseLevelOrder(Node*root){vector<int>result;// If the tree is empty, return an empty result.if(root==nullptr)returnresult;queue<Node*>q;// Store each level separately.vector<vector<int>>levels;// Start BFS traversal from the root.q.push(root);while(!q.empty()){// Number of nodes present at the current level.intsize=q.size();vector<int>currentLevel;// Process all nodes of the current level.for(inti=0;i<size;i++){Node*curr=q.front();q.pop();// Store the current node's value.currentLevel.push_back(curr->data);// Push the left child first.if(curr->left)q.push(curr->left);// Push the right child.if(curr->right)q.push(curr->right);}// Store the current level.levels.push_back(currentLevel);}// Traverse the levels from bottom to top.for(inti=levels.size()-1;i>=0;i--){for(intvalue:levels[i]){result.push_back(value);}}returnresult;}intmain(){/* 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);for(intx:result)cout<<x<<" ";return0;}
Java
importjava.util.*;/* Structure of Tree Node */classNode{intdata;Nodeleft;Noderight;Node(intval){data=val;left=right=null;}}classGFG{staticList<Integer>reverseLevelOrder(Noderoot){List<Integer>result=newArrayList<>();// If the tree is empty, return an empty result.if(root==null)returnresult;Queue<Node>q=newLinkedList<>();// Store each level separately.List<List<Integer>>levels=newArrayList<>();// Start BFS traversal from the root.q.add(root);while(!q.isEmpty()){// Number of nodes present at the current level.intsize=q.size();List<Integer>currentLevel=newArrayList<>();// Process all nodes of the current level.for(inti=0;i<size;i++){Nodecurr=q.poll();// Store the current node's value.currentLevel.add(curr.data);// Push the left child first.if(curr.left!=null)q.add(curr.left);// Push the right child.if(curr.right!=null)q.add(curr.right);}// Store the current level.levels.add(currentLevel);}// Traverse the levels from bottom to top.for(inti=levels.size()-1;i>=0;i--){for(intvalue:levels.get(i)){result.add(value);}}returnresult;}publicstaticvoidmain(String[]args){/* 1 / \ 2 3 / \ 4 5 */Noderoot=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);for(intx:result)System.out.print(x+" ");}}
Python
fromcollectionsimportdeque# Structure of Tree NodeclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=NonedefreverseLevelOrder(root):result=[]# If the tree is empty, return an empty result.ifrootisNone:returnresultq=deque()# Store each level separately.levels=[]# Start BFS traversal from the root.q.append(root)whileq:# Number of nodes present at the current level.size=len(q)currentLevel=[]# Process all nodes of the current level.foriinrange(size):curr=q.popleft()# Store the current node's value.currentLevel.append(curr.data)# Push the left child first.ifcurr.leftisnotNone:q.append(curr.left)# Push the right child.ifcurr.rightisnotNone:q.append(curr.right)# Store the current level.levels.append(currentLevel)# Traverse the levels from bottom to top.foriinrange(len(levels)-1,-1,-1):forvalueinlevels[i]:result.append(value)returnresult# Driver Codeif__name__=="__main__":""" 1 / \ 2 3 / \ 4 5 """root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)result=reverseLevelOrder(root)forxinresult:print(x,end=" ")
C#
usingSystem;usingSystem.Collections.Generic;/* Structure of Tree Node */classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}classGFG{staticList<int>reverseLevelOrder(Noderoot){List<int>result=newList<int>();// If the tree is empty, return an empty result.if(root==null)returnresult;Queue<Node>q=newQueue<Node>();// Store each level separately.List<List<int>>levels=newList<List<int>>();// Start BFS traversal from the root.q.Enqueue(root);while(q.Count>0){// Number of nodes present at the current level.intsize=q.Count;List<int>currentLevel=newList<int>();// Process all nodes of the current level.for(inti=0;i<size;i++){Nodecurr=q.Dequeue();// Store the current node's value.currentLevel.Add(curr.data);// Push the left child first.if(curr.left!=null)q.Enqueue(curr.left);// Push the right child.if(curr.right!=null)q.Enqueue(curr.right);}// Store the current level.levels.Add(currentLevel);}// Traverse the levels from bottom to top.for(inti=levels.Count-1;i>=0;i--){foreach(intvalueinlevels[i]){result.Add(value);}}returnresult;}staticvoidMain(){/* 1 / \ 2 3 / \ 4 5 */Noderoot=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);foreach(intxinresult)Console.Write(x+" ");}}
JavaScript
/* Structure of Tree Node */classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functionreverseLevelOrder(root){letresult=[];// If the tree is empty, return an empty result.if(root===null)returnresult;letq=[];letfront=0;// Store each level separately.letlevels=[];// Start BFS traversal from the root.q.push(root);while(front<q.length){// Number of nodes present at the current level.letsize=q.length-front;letcurrentLevel=[];// Process all nodes of the current level.for(leti=0;i<size;i++){letcurr=q[front++];// Store the current node's value.currentLevel.push(curr.data);// Push the left child first.if(curr.left!==null)q.push(curr.left);// Push the right child.if(curr.right!==null)q.push(curr.right);}// Store the current level.levels.push(currentLevel);}// Traverse the levels from bottom to top.for(leti=levels.length-1;i>=0;i--){for(letvalueoflevels[i]){result.push(value);}}returnresult;}// Driver Code/* 1 / \ 2 3 / \ 4 5 */letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);letresult=reverseLevelOrder(root);console.log(result.join(" "));
Output
4 5 2 3 1
[Expected Approach] Queue + Stack - O(n) Time and O(n) Space
Instead of storing levels separately, we can use a queue for BFS and a stack to reverse the traversal order. The important trick is to push the right child before the left child into the queue. This ensures that when we later pop nodes from the stack, the nodes within each level appear in the required left-to-right order.
If the tree is empty, return an empty result.
Use a queue for BFS and a stack to store visited nodes.
Remove each node from the queue and push it into the stack.
Add the right child first, followed by the left child, to the queue.
Pop all nodes from the stack and add their values to the result.
Return the result.
C++
#include<bits/stdc++.h>usingnamespacestd;/* Structure of Tree Node */classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};vector<int>reverseLevelOrder(Node*root){vector<int>result;// If the tree is empty, return an empty result.if(root==nullptr)returnresult;queue<Node*>q;stack<Node*>st;// Start BFS traversal from the root.q.push(root);while(!q.empty()){// Remove the front node from the queue.Node*curr=q.front();q.pop();// Store the current node in the stack.st.push(curr);// Push the right child first.if(curr->right)q.push(curr->right);// Push the left child after the right child.if(curr->left)q.push(curr->left);}// Pop nodes from the stack to get// reverse level order traversal.while(!st.empty()){Node*curr=st.top();st.pop();// Store the current node's value.result.push_back(curr->data);}returnresult;}intmain(){/* 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);for(intx:result)cout<<x<<" ";return0;}
Java
importjava.util.*;/* Structure of Tree Node */classNode{intdata;Nodeleft;Noderight;Node(intval){data=val;left=right=null;}}classGFG{staticList<Integer>reverseLevelOrder(Noderoot){List<Integer>result=newArrayList<>();// If the tree is empty, return an empty result.if(root==null)returnresult;Queue<Node>q=newLinkedList<>();Stack<Node>st=newStack<>();// Start BFS traversal from the root.q.add(root);while(!q.isEmpty()){// Remove the front node from the queue.Nodecurr=q.poll();// Store the current node in the stack.st.push(curr);// Push the right child first.if(curr.right!=null)q.add(curr.right);// Push the left child after the right child.if(curr.left!=null)q.add(curr.left);}// Pop nodes from the stack to get// reverse level order traversal.while(!st.isEmpty()){Nodecurr=st.pop();// Store the current node's value.result.add(curr.data);}returnresult;}publicstaticvoidmain(String[]args){/* 1 / \ 2 3 / \ 4 5 */Noderoot=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);for(intx:result)System.out.print(x+" ");}}
Python
fromcollectionsimportdeque# Structure of Tree NodeclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=NonedefreverseLevelOrder(root):result=[]# If the tree is empty, return an empty result.ifrootisNone:returnresultq=deque()st=[]# Start BFS traversal from the root.q.append(root)whileq:# Remove the front node from the queue.curr=q.popleft()# Store the current node in the stack.st.append(curr)# Push the right child first.ifcurr.rightisnotNone:q.append(curr.right)# Push the left child after the right child.ifcurr.leftisnotNone:q.append(curr.left)# Pop nodes from the stack to get# reverse level order traversal.whilest:curr=st.pop()# Store the current node's value.result.append(curr.data)returnresult# Driver Codeif__name__=="__main__":""" 1 / \ 2 3 / \ 4 5 """root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)result=reverseLevelOrder(root)forxinresult:print(x,end=" ")
C#
usingSystem;usingSystem.Collections.Generic;/* Structure of Tree Node */classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}classGFG{staticList<int>reverseLevelOrder(Noderoot){List<int>result=newList<int>();// If the tree is empty, return an empty result.if(root==null)returnresult;Queue<Node>q=newQueue<Node>();Stack<Node>st=newStack<Node>();// Start BFS traversal from the root.q.Enqueue(root);while(q.Count>0){// Remove the front node from the queue.Nodecurr=q.Dequeue();// Store the current node in the stack.st.Push(curr);// Push the right child first.if(curr.right!=null)q.Enqueue(curr.right);// Push the left child after the right child.if(curr.left!=null)q.Enqueue(curr.left);}// Pop nodes from the stack to get// reverse level order traversal.while(st.Count>0){Nodecurr=st.Pop();// Store the current node's value.result.Add(curr.data);}returnresult;}staticvoidMain(){/* 1 / \ 2 3 / \ 4 5 */Noderoot=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);foreach(intxinresult)Console.Write(x+" ");}}
JavaScript
/* Structure of Tree Node */classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functionreverseLevelOrder(root){letresult=[];// If the tree is empty, return an empty result.if(root===null)returnresult;letq=[];letst=[];letfront=0;// Start BFS traversal from the root.q.push(root);while(front<q.length){// Remove the front node from the queue.letcurr=q[front++];// Store the current node in the stack.st.push(curr);// Push the right child first.if(curr.right!==null)q.push(curr.right);// Push the left child after the right child.if(curr.left!==null)q.push(curr.left);}// Pop nodes from the stack to get// reverse level order traversal.while(st.length>0){letcurr=st.pop();// Store the current node's value.result.push(curr.data);}returnresult;}// Driver Code/* 1 / \ 2 3 / \ 4 5 */letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);letresult=reverseLevelOrder(root);letres=""for(letxofresult){res+=x+" ";}console.log(res);