We have discussed the level-order traversal of a tree in the previous post. 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.
The reverse Level order traversal of the above tree is “4 5 2 3 1”. Both methods for normal level order traversal can be easily modified to do reverse level order traversal.
METHOD 1 (Recursive function to print a given level) We can easily modify method 1 of the normal level order traversal. In method 1, we have a method printGivenLevel() which prints a given level number. The only thing we need to change is, instead of calling printGivenLevel() from the first level to the last level, we call it from the last level to the first level.
C++
// A recursive C++ program to print
// REVERSE level order traversal
#include <bits/stdc++.h>
usingnamespacestd;
/* A binary tree node has data,
pointer to left and right child */
classnode
{
public:
intdata;
node* left;
node* right;
};
/*Function prototypes*/
voidprintGivenLevel(node* root, intlevel);
intheight(node* node);
node* newNode(intdata);
/* Function to print REVERSE
level order traversal a tree*/
voidreverseLevelOrder(node* root)
{
inth = height(root);
inti;
for(i=h; i>=1; i--) //THE ONLY LINE DIFFERENT FROM NORMAL LEVEL ORDER
printGivenLevel(root, i);
}
/* Print nodes at a given level */
voidprintGivenLevel(node* root, intlevel)
{
if(root == NULL)
return;
if(level == 1)
cout << root->data << " ";
elseif(level > 1)
{
printGivenLevel(root->left, level - 1);
printGivenLevel(root->right, level - 1);
}
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
intheight(node* node)
{
if(node == NULL)
return0;
else
{
/* compute the height of each subtree */
intlheight = height(node->left);
intrheight = height(node->right);
/* use the larger one */
if(lheight > rheight)
return(lheight + 1);
elsereturn(rheight + 1);
}
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newNode(intdata)
{
node* Node = newnode();
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return(Node);
}
/* Driver code*/
intmain()
{
node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << "Level Order traversal of binary tree is \n";
reverseLevelOrder(root);
return0;
}
// This code is contributed by rathbhupendra
C
// A recursive C program to print REVERSE level order traversal
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer to left and right child */
structnode
{
intdata;
structnode* left;
structnode* right;
};
/*Function prototypes*/
voidprintGivenLevel(structnode* root, intlevel);
intheight(structnode* node);
structnode* newNode(intdata);
/* Function to print REVERSE level order traversal a tree*/
voidreverseLevelOrder(structnode* root)
{
inth = height(root);
inti;
for(i=h; i>=1; i--) //THE ONLY LINE DIFFERENT FROM NORMAL LEVEL ORDER
printGivenLevel(root, i);
}
/* Print nodes at a given level */
voidprintGivenLevel(structnode* root, intlevel)
{
if(root == NULL)
return;
if(level == 1)
printf("%d ", root->data);
elseif(level > 1)
{
printGivenLevel(root->left, level-1);
printGivenLevel(root->right, level-1);
}
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
intheight(structnode* node)
{
if(node==NULL)
return0;
else
{
/* compute the height of each subtree */
intlheight = height(node->left);
intrheight = height(node->right);
/* use the larger one */
if(lheight > rheight)
return(lheight+1);
elsereturn(rheight+1);
}
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
structnode* newNode(intdata)
{
structnode* node = (structnode*)
malloc(sizeof(structnode));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above functions*/
intmain()
{
structnode *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Level Order traversal of binary tree is \n");
reverseLevelOrder(root);
return0;
}
Java
// A recursive java program to print reverse level order traversal
// A binary tree node
classNode
{
intdata;
Node left, right;
Node(intitem)
{
data = item;
left = right;
}
}
classBinaryTree
{
Node root;
/* Function to print REVERSE level order traversal a tree*/
voidreverseLevelOrder(Node node)
{
inth = height(node);
inti;
for(i = h; i >= 1; i--)
//THE ONLY LINE DIFFERENT FROM NORMAL LEVEL ORDER
{
printGivenLevel(node, i);
}
}
/* Print nodes at a given level */
voidprintGivenLevel(Node node, intlevel)
{
if(node == null)
return;
if(level == 1)
System.out.print(node.data + " ");
elseif(level > 1)
{
printGivenLevel(node.left, level - 1);
printGivenLevel(node.right, level - 1);
}
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
intheight(Node node)
{
if(node == null)
return0;
else
{
/* compute the height of each subtree */
intlheight = height(node.left);
intrheight = height(node.right);
/* use the larger one */
if(lheight > rheight)
return(lheight + 1);
else
return(rheight + 1);
}
}
// Driver program to test above functions
publicstaticvoidmain(String args[])
{
BinaryTree tree = newBinaryTree();
// Let us create trees shown in above diagram
tree.root = newNode(1);
tree.root.left = newNode(2);
tree.root.right = newNode(3);
tree.root.left.left = newNode(4);
tree.root.left.right = newNode(5);
System.out.println("Level Order traversal of binary tree is : ");
tree.reverseLevelOrder(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal
Python
# A recursive Python program to print REVERSE level order traversal
# A binary tree node
classNode:
# Constructor to create a new node
def__init__(self, data):
self.data =data
self.left =None
self.right =None
# Function to print reverse level order traversal
defreverseLevelOrder(root):
h =height(root)
fori inreversed(range(1, h+1)):
printGivenLevel(root,i)
# Print nodes at a given level
defprintGivenLevel(root, level):
ifroot isNone:
return
iflevel ==1:
printroot.data,
eliflevel>1:
printGivenLevel(root.left, level-1)
printGivenLevel(root.right, level-1)
# Compute the height of a tree-- the number of
# nodes along the longest path from the root node
# down to the farthest leaf node
defheight(node):
ifnode isNone:
return0
else:
# Compute the height of each subtree
lheight =height(node.left)
rheight =height(node.right)
# Use the larger one
iflheight > rheight :
returnlheight +1
else:
returnrheight +1
# Driver program to test above function
root =Node(1)
root.left =Node(2)
root.right =Node(3)
root.left.left =Node(4)
root.left.right =Node(5)
print"Level Order traversal of binary tree is"
reverseLevelOrder(root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
C#
// A recursive C# program to print
// reverse level order traversal
usingSystem;
// A binary tree node
classNode
{
publicintdata;
publicNode left, right;
publicNode(intitem)
{
data = item;
left = right;
}
}
classBinaryTree
{
Node root;
/* Function to print REVERSE
level order traversal a tree*/
voidreverseLevelOrder(Node node)
{
inth = height(node);
inti;
for(i = h; i >= 1; i--)
// THE ONLY LINE DIFFERENT
// FROM NORMAL LEVEL ORDER
{
printGivenLevel(node, i);
}
}
/* Print nodes at a given level */
voidprintGivenLevel(Node node, intlevel)
{
if(node == null)
return;
if(level == 1)
Console.Write(node.data + " ");
elseif(level > 1)
{
printGivenLevel(node.left, level - 1);
printGivenLevel(node.right, level - 1);
}
}
/* Compute the "height" of a tree --
the number of nodes along the longest
path from the root node down to the
farthest leaf node.*/
intheight(Node node)
{
if(node == null)
return0;
else
{
/* compute the height of each subtree */
intlheight = height(node.left);
intrheight = height(node.right);
/* use the larger one */
if(lheight > rheight)
return(lheight + 1);
else
return(rheight + 1);
}
}
// Driver Code
staticpublicvoidMain(String []args)
{
BinaryTree tree = newBinaryTree();
// Let us create trees shown
// in above diagram
tree.root = newNode(1);
tree.root.left = newNode(2);
tree.root.right = newNode(3);
tree.root.left.left = newNode(4);
tree.root.left.right = newNode(5);
Console.WriteLine("Level Order traversal "+
"of binary tree is : ");
tree.reverseLevelOrder(tree.root);
}
}
// This code is contributed
// by Arnab Kundu
Javascript
<script>
// A recursive JavaScript program to print
// reverse level order traversal
// A binary tree node
class Node {
constructor(item) {
this.data = item;
this.left = null;
this.right = null;
}
}
class BinaryTree {
constructor() {
this.root = null;
}
/* Function to print REVERSE
level order traversal a tree*/
reverseLevelOrder(node) {
varh = this.height(node);
vari;
for(
i = h;
i >= 1;
i-- // THE ONLY LINE DIFFERENT // FROM NORMAL LEVEL ORDER
) {
this.printGivenLevel(node, i);
}
}
/* Print nodes at a given level */
printGivenLevel(node, level) {
if(node == null) return;
if(level == 1) document.write(node.data + " ");
elseif(level > 1) {
this.printGivenLevel(node.left, level - 1);
this.printGivenLevel(node.right, level - 1);
}
}
/* Compute the "height" of a tree --
the number of nodes along the longest
path from the root node down to the
farthest leaf node.*/
height(node) {
if(node == null) return0;
else{
/* compute the height of each subtree */
varlheight = this.height(node.left);
varrheight = this.height(node.right);
/* use the larger one */
if(lheight > rheight) returnlheight + 1;
elsereturnrheight + 1;
}
}
}
// Driver Code
vartree = newBinaryTree();
// Let us create trees shown
// in above diagram
tree.root = newNode(1);
tree.root.left = newNode(2);
tree.root.right = newNode(3);
tree.root.left.left = newNode(4);
tree.root.left.right = newNode(5);
document.write(
"Level Order traversal "+ "of binary tree is : <br>"
);
tree.reverseLevelOrder(tree.root);
</script>
Output
Level Order traversal of binary tree is
4 5 2 3 1
Time Complexity: O(n^2) Auxiliary Space: O(h), where h is the height of the tree, this space is due to the recursive call stack.
METHOD 2 (Using Queue and Stack) The idea is to use a deque(double-ended queue) to get the reverse level order. A deque allows insertion and deletion at both ends. If we do normal level order traversal and instead of printing a node, push the node to a stack and then print the contents of the deque, we get “5 4 3 2 1” for the above example tree, but the output should be “4 5 2 3 1”. So to get the correct sequence (left to right at every level), we process the children of a node in reverse order, we first push the right subtree to the deque, then process the left subtree.
C++
// A C++ program to print REVERSE level order traversal using stack and queue
/* A binary tree node has data, pointer to left and right children */
structnode
{
intdata;
structnode* left;
structnode* right;
};
/* Given a binary tree, print its nodes in reverse level order */
voidreverseLevelOrder(node* root)
{
stack <node *> S;
queue <node *> Q;
Q.push(root);
// Do something like normal level order traversal order. Following are the
// differences with normal level order traversal
// 1) Instead of printing a node, we push the node to stack
// 2) Right subtree is visited before left subtree
while(Q.empty() == false)
{
/* Dequeue node and make it root */
root = Q.front();
Q.pop();
S.push(root);
/* Enqueue right child */
if(root->right)
Q.push(root->right); // NOTE: RIGHT CHILD IS ENQUEUED BEFORE LEFT
/* Enqueue left child */
if(root->left)
Q.push(root->left);
}
// Now pop all items from stack one by one and print them
while(S.empty() == false)
{
root = S.top();
cout << root->data << " ";
S.pop();
}
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newNode(intdata)
{
node* temp = newnode;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return(temp);
}
/* Driver program to test above functions*/
intmain()
{
structnode *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
cout << "Level Order traversal of binary tree is \n";
reverseLevelOrder(root);
return0;
}
Java
// A recursive java program to print reverse level order traversal
// using stack and queue
importjava.util.LinkedList;
importjava.util.Queue;
importjava.util.Stack;
/* A binary tree node has data, pointer to left and right children */
classNode
{
intdata;
Node left, right;
Node(intitem)
{
data = item;
left = right;
}
}
classBinaryTree
{
Node root;
/* Given a binary tree, print its nodes in reverse level order */
voidreverseLevelOrder(Node node)
{
Stack<Node> S = newStack();
Queue<Node> Q = newLinkedList();
Q.add(node);
// Do something like normal level order traversal order.Following
// are the differences with normal level order traversal
// 1) Instead of printing a node, we push the node to stack
// 2) Right subtree is visited before left subtree
while(Q.isEmpty() == false)
{
/* Dequeue node and make it root */
node = Q.peek();
Q.remove();
S.push(node);
/* Enqueue right child */
if(node.right != null)
// NOTE: RIGHT CHILD IS ENQUEUED BEFORE LEFT
Q.add(node.right);
/* Enqueue left child */
if(node.left != null)
Q.add(node.left);
}
// Now pop all items from stack one by one and print them
while(S.empty() == false)
{
node = S.peek();
System.out.print(node.data + " ");
S.pop();
}
}
// Driver program to test above functions
publicstaticvoidmain(String args[])
{
BinaryTree tree = newBinaryTree();
// Let us create trees shown in above diagram
tree.root = newNode(1);
tree.root.left = newNode(2);
tree.root.right = newNode(3);
tree.root.left.left = newNode(4);
tree.root.left.right = newNode(5);
tree.root.right.left = newNode(6);
tree.root.right.right = newNode(7);
System.out.println("Level Order traversal of binary tree is :");
tree.reverseLevelOrder(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal
Python
# Python program to print REVERSE level order traversal using
# stack and queue
fromcollections importdeque
# A binary tree node
classNode:
# Constructor to create a new node
def__init__(self, data):
self.data =data
self.left =None
self.right =None
# Given a binary tree, print its nodes in reverse level order
defreverseLevelOrder(root):
# we can use a double ended queue which provides O(1) insert at the beginning
# using the appendleft method
# we do the regular level order traversal but instead of processing the
# left child first we process the right child first and the we process the left child
# of the current Node
# we can do this One pass reduce the space usage not in terms of complexity but intuitively
q =deque()
q.append(root)
ans =deque()
whileq:
node =q.popleft()
ifnode isNone:
continue
ans.appendleft(node.data)
ifnode.right:
q.append(node.right)
ifnode.left:
q.append(node.left)
returnans
# Driver program to test above function
root =Node(1)
root.left =Node(2)
root.right =Node(3)
root.left.left =Node(4)
root.left.right =Node(5)
root.right.left =Node(6)
root.right.right =Node(7)
print"Level Order traversal of binary tree is"
deq =reverseLevelOrder(root)
forkey indeq:
print(key),
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
C#
// A recursive C# program to print reverse
// level order traversal using stack and queue
usingSystem.Collections.Generic;
usingSystem;
/* A binary tree node has data,
pointer to left and right children */
publicclassNode
{
publicintdata;
publicNode left, right;
publicNode(intitem)
{
data = item;
left = right;
}
}
publicclassBinaryTree
{
Node root;
/* Given a binary tree, print its
nodes in reverse level order */
voidreverseLevelOrder(Node node)
{
Stack<Node> S = newStack<Node>();
Queue<Node> Q = newQueue<Node>();
Q.Enqueue(node);
// Do something like normal level
// order traversal order.Following
// are the differences with normal
// level order traversal
// 1) Instead of printing a node, we push the node to stack
// 2) Right subtree is visited before left subtree
while(Q.Count>0)
{
/* Dequeue node and make it root */
node = Q.Peek();
Q.Dequeue();
S.Push(node);
/* Enqueue right child */
if(node.right != null)
// NOTE: RIGHT CHILD IS ENQUEUED BEFORE LEFT
Q.Enqueue(node.right);
/* Enqueue left child */
if(node.left != null)
Q.Enqueue(node.left);
}
// Now pop all items from stack
// one by one and print them
while(S.Count>0)
{
node = S.Peek();
Console.Write(node.data + " ");
S.Pop();
}
}
// Driver code
publicstaticvoidMain()
{
BinaryTree tree = newBinaryTree();
// Let us create trees shown in above diagram
tree.root = newNode(1);
tree.root.left = newNode(2);
tree.root.right = newNode(3);
tree.root.left.left = newNode(4);
tree.root.left.right = newNode(5);
tree.root.right.left = newNode(6);
tree.root.right.right = newNode(7);
Console.WriteLine("Level Order traversal of binary tree is :");
tree.reverseLevelOrder(tree.root);
}
}
/* This code contributed by PrinciRaj1992 */
Javascript
<script>
// A recursive javascript program to print
// reverse level order traversal
// using stack and queue
/* A binary tree node has data, pointer to left
and right children */
class Node
{
constructor(item)
{
this.data = item;
this.left = this.right=null;
}
}
let root;
/* Given a binary tree, print its nodes in reverse level order */
functionreverseLevelOrder(node)
{
let S = [];
let Q = [];
Q.push(node);
// Do something like normal
// level order traversal order.Following
// are the differences with normal
// level order traversal
// 1) Instead of printing a node,
// we push the node to stack
// 2) Right subtree is visited before left subtree
while(Q.length != 0)
{
/* Dequeue node and make it root */
node = Q[0];
Q.shift();
S.push(node);
/* Enqueue right child */
if(node.right != null)
// NOTE: RIGHT CHILD IS ENQUEUED BEFORE LEFT
Q.push(node.right);
/* Enqueue left child */
if(node.left != null)
Q.push(node.left);
}
// Now pop all items from stack
// one by one and print them
while(S.length != 0)
{
node = S.pop();
document.write(node.data + " ");
}
}
// Driver program to test above functions
// Let us create trees shown in above diagram
root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
document.write("Level Order traversal of binary tree is :<br>");
reverseLevelOrder(root);
// This code is contributed by avanitrachhadiya2155
</script>
Output
Level Order traversal of binary tree is
4 5 6 7 2 3 1
Time Complexity: O(n), where n is the number of nodes in the binary tree. Auxiliary Space: O(n),for stack and queue.
Method 3: ( Using a Hash_Map)
The basic idea behind this approach is to use a hashmap to store the nodes at each level of the binary tree, and then iterate over the hashmap in reverse order of the levels to obtain the reverse level order traversal.
Follow the steps to implement above idea:
Define a Node struct to represent a binary tree node.
Define a recursive function addNodesToMap that takes a binary tree node, a level, and a reference to an unordered map, and adds the node to the vector of nodes at its level in the unordered map. This function should then recursively call itself on the left and right subtrees.
Define the main reverseLevelOrder function that takes the root of the binary tree as input, and returns a vector containing the nodes in reverse level order.
Inside the reverseLevelOrder function, create an unordered map to store the nodes at each level of the binary tree.
Call the addNodesToMap function on the root of the binary tree, with level 0 and a reference to the unordered map, to populate the map with nodes.
Iterate over the unordered map in reverse order of the levels, and add the nodes to the result vector in the order they appear in the vectors in the unordered map.
Return the result vector containing the nodes in reverse level order.
Below is the implementation:
C++
// C++ code to implement the hash_map approach
#include <bits/stdc++.h>
#include <unordered_map>
usingnamespacestd;
// Definition of a binary tree node
structNode {
intdata;
Node* left;
Node* right;
Node(intval)
{
data = val;
left = right = nullptr;
}
};
// Recursive function to traverse the binary
// tree and add nodes to the hashmap
voidaddNodesToMap(
Node* node, intlevel,
unordered_map<int, vector<int> >& nodeMap)
{
if(node == nullptr) {
return;
}
// Add the current node to the vector of
// nodes at its level in the hashmap
nodeMap[level].push_back(node->data);
// Recursively traverse the left and
// right subtrees
addNodesToMap(node->left, level + 1, nodeMap);
addNodesToMap(node->right, level + 1, nodeMap);
}
vector<int> reverseLevelOrder(Node* root)
{
vector<int> result;
// Create an unordered_map to store the
// nodes at each level of the binary tree
unordered_map<int, vector<int> > nodeMap;
// Traverse the binary tree recursively and
// add nodes to the hashmap
addNodesToMap(root, 0, nodeMap);
// Iterate over the hashmap in reverse order of the
// levels and add nodes to the result vector
for(intlevel = nodeMap.size() - 1; level >= 0;
level--) {
vector<int> nodesAtLevel = nodeMap[level];
for(inti = 0; i < nodesAtLevel.size(); i++) {
result.push_back(nodesAtLevel[i]);
}
}
returnresult;
}
// Driver code
intmain()
{
// Create the binary tree
Node* root = newNode(10);
root->left = newNode(20);
root->right = newNode(30);
root->left->left = newNode(40);
root->left->right = newNode(60);
// Find the reverse level order traversal
// of the binary tree
vector<int> result = reverseLevelOrder(root);
cout << "Level Order traversal of binary tree is:"
<< endl;
// Print the result
for(inti = 0; i < result.size(); i++) {
cout << result[i] << " ";
}
cout << endl;
return0;
}
//This code is contributed by Veerendra_Singh_Rajpoot
System.out.println("Level Order traversal of binary tree is:");
// Print the result
for(inti = 0; i < result.size(); i++) {
System.out.print(result.get(i) + " ");
}
System.out.println();
}
}
// This code is contributed by Veerendra_Singh_Rajpoot
Python
classNode:
def__init__(self, val):
self.data =val
self.left =None
self.right =None
# Recursive function to traverse the binary
defaddNodesToMap(node, level, nodeMap):
ifnode isNone:
return
iflevel innodeMap:
nodeMap[level].append(node.data)
else:
nodeMap[level] =[node.data]
# Recursively traverse the left and right subtrees
addNodesToMap(node.left, level +1, nodeMap)
addNodesToMap(node.right, level +1, nodeMap)
defGFG(root):
result =[]
nodeMap ={}
# Traverse the binary tree recursively
addNodesToMap(root, 0, nodeMap)
# Iterate over the dictionary in reverse order
forlevel inrange(len(nodeMap) -1, -1, -1):
nodesAtLevel =nodeMap[level]
result.extend(nodesAtLevel)
returnresult
# Driver code
if__name__ =="__main__":
# Create the binary tree
root =Node(10)
root.left =Node(20)
root.right =Node(30)
root.left.left =Node(40)
root.left.right =Node(60)
# Find the reverse level order traversal of the binary tree
result =GFG(root)
print("Level Order traversal of binary tree is:")
# Print the result without brackets
print(" ".join(map(str, result)))
C#
usingSystem;
usingSystem.Collections.Generic;
// Definition of a binary tree node
classNode {
publicintdata;
publicNode left;
publicNode right;
publicNode(intval)
{
data = val;
left = right = null;
}
}
classProgram {
// Recursive function to traverse the binary
// tree and add nodes to the hashmap
staticvoid
AddNodesToMap(Node node, intlevel,
Dictionary<int, List<int> > nodeMap)
{
if(node == null) {
return;
}
// Add the current node to the list of
// nodes at its level in the hashmap
if(!nodeMap.ContainsKey(level)) {
nodeMap[level] = newList<int>();
}
nodeMap[level].Add(node.data);
// Recursively traverse the left and
// right subtrees
AddNodesToMap(node.left, level + 1, nodeMap);
AddNodesToMap(node.right, level + 1, nodeMap);
}
staticList<int> ReverseLevelOrder(Node root)
{
List<int> result = newList<int>();
// Create a dictionary to store the
// nodes at each level of the binary tree
Dictionary<int, List<int> > nodeMap
= newDictionary<int, List<int> >();
// Traverse the binary tree recursively and
// add nodes to the dictionary
AddNodesToMap(root, 0, nodeMap);
// Iterate over the dictionary in reverse order of
// the levels and add nodes to the result list
for(intlevel = nodeMap.Count - 1; level >= 0;
level--) {
List<int> nodesAtLevel = nodeMap[level];
for(inti = 0; i < nodesAtLevel.Count; i++) {
result.Add(nodesAtLevel[i]);
}
}
returnresult;
}
// Driver code
staticvoidMain()
{
// Create the binary tree
Node root = newNode(10);
root.left = newNode(20);
root.right = newNode(30);
root.left.left = newNode(40);
root.left.right = newNode(60);
// Find the reverse level order traversal
// of the binary tree
List<int> result = ReverseLevelOrder(root);
Console.WriteLine(
"Level Order traversal of binary tree is:");
// Print the result
foreach(intval inresult)
{
Console.Write(val + " ");
}
Console.WriteLine();
}
}
Javascript
// Definition of a binary tree node
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
// Recursive function to traverse the binary
// tree and add nodes to the hashmap
functionaddNodesToMap(node, level, nodeMap) {
if(node === null) {
return;
}
// Add the current node to the vector of
// nodes at its level in the hashmap
if(!nodeMap[level]) {
nodeMap[level] = [];
}
nodeMap[level].push(node.data);
// Recursively traverse the left and
// right subtrees
addNodesToMap(node.left, level + 1, nodeMap);
addNodesToMap(node.right, level + 1, nodeMap);
}
functionreverseLevelOrder(root) {
const result = [];
// Create an object to store the nodes at each level of the binary tree
const nodeMap = {};
// Traverse the binary tree recursively and
// add nodes to the hashmap
addNodesToMap(root, 0, nodeMap);
// Iterate over the hashmap in reverse order of the
// levels and add nodes to the result array
const levels = Object.keys(nodeMap).map(Number);
levels.sort((a, b) => b - a); // Sort levels in reverse order
for(const level of levels) {
result.push(...nodeMap[level]);
}
returnresult;
}
// Driver code
// Create the binary tree
const root = newNode(10);
root.left = newNode(20);
root.right = newNode(30);
root.left.left = newNode(40);
root.left.right = newNode(60);
// Find the reverse level order traversal
// of the binary tree
const result = reverseLevelOrder(root);
console.log("Level Order traversal of binary tree is:");
// Print the result
console.log(result.join(" "));
// This code is contributed by Veerendra_Singh_Rajpoot
Output
Level Order traversal of binary tree is:
40 60 20 30 10
Time complexity: O(n) – where n is the number of nodes in the binary tree. Auxiliary Space: O(n) – where n is the number of nodes in the binary tree.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!