Reverse Level Order Traversal

16 Mar, 2022
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. 
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 the 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.  
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
C++
C
Java
Python
C#
Javascript
// A recursive C++ program to print// REVERSE level order traversal#include <bits/stdc++.h>using namespace std; /* A binary tree node has data,pointer to left and right child */class node{    public:    int data;    node* left;    node* right;}; /*Function prototypes*/void printGivenLevel(node* root, int level);int height(node* node);node* newNode(int data); /* Function to print REVERSElevel order traversal a tree*/void reverseLevelOrder(node* root){    int h = height(root);    int i;    for (i=h; i>=1; i--) //THE ONLY LINE DIFFERENT FROM NORMAL LEVEL ORDER        printGivenLevel(root, i);} /* Print nodes at a given level */void printGivenLevel(node* root, int level){    if (root == NULL)        return;    if (level == 1)        cout << root->data << " ";    else if (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.*/int height(node* node){    if (node == NULL)        return 0;    else    {        /* compute the height of each subtree */        int lheight = height(node->left);        int rheight = height(node->right);         /* use the larger one */        if (lheight > rheight)            return(lheight + 1);        else return(rheight + 1);    }} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){    node* Node = new node();    Node->data = data;    Node->left = NULL;    Node->right = NULL;     return(Node);} /* Driver code*/int main(){    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);     return 0; } // This code is contributed by rathbhupendra
// 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 */struct node{    int data;    struct node* left;    struct node* right;}; /*Function prototypes*/void printGivenLevel(struct node* root, int level);int height(struct node* node);struct node* newNode(int data); /* Function to print REVERSE level order traversal a tree*/void reverseLevelOrder(struct node* root){    int h = height(root);    int i;    for (i=h; i>=1; i--) //THE ONLY LINE DIFFERENT FROM NORMAL LEVEL ORDER        printGivenLevel(root, i);} /* Print nodes at a given level */void printGivenLevel(struct node* root, int level){    if (root == NULL)        return;    if (level == 1)        printf("%d ", root->data);    else if (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.*/int height(struct node* node){    if (node==NULL)        return 0;    else    {        /* compute the height of each subtree */        int lheight = height(node->left);        int rheight = height(node->right);         /* use the larger one */        if (lheight > rheight)            return(lheight+1);        else return(rheight+1);    }} /* Helper function that allocates a new node with the   given data and NULL left and right pointers. */struct node* newNode(int data){    struct node* node = (struct node*)                        malloc(sizeof(struct node));    node->data = data;    node->left = NULL;    node->right = NULL;     return(node);} /* Driver program to test above functions*/int main(){    struct node *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);     return 0;}
// A recursive java program to print reverse level order traversal  // A binary tree nodeclass Node{    int data;    Node left, right;          Node(int item)    {        data = item;        left = right;    }}  class BinaryTree{    Node root;      /* Function to print REVERSE level order traversal a tree*/    void reverseLevelOrder(Node node)    {        int h = height(node);        int i;        for (i = h; i >= 1; i--)        //THE ONLY LINE DIFFERENT FROM NORMAL LEVEL ORDER        {            printGivenLevel(node, i);        }    }      /* Print nodes at a given level */    void printGivenLevel(Node node, int level)    {        if (node == null)            return;        if (level == 1)            System.out.print(node.data + " ");        else if (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.*/    int height(Node node)    {        if (node == null)            return 0;        else        {            /* compute the height of each subtree */            int lheight = height(node.left);            int rheight = height(node.right);              /* use the larger one */            if (lheight > rheight)                return (lheight + 1);            else                return (rheight + 1);        }    }      // Driver program to test above functions    public static void main(String args[])    {        BinaryTree tree = new BinaryTree();          // Let us create trees shown in above diagram        tree.root = new Node(1);        tree.root.left = new Node(2);        tree.root.right = new Node(3);        tree.root.left.left = new Node(4);        tree.root.left.right = new Node(5);                  System.out.println("Level Order traversal of binary tree is : ");        tree.reverseLevelOrder(tree.root);    }}  // This code has been contributed by Mayank Jaiswal
# A recursive Python program to print REVERSE level order traversal # A binary tree nodeclass Node:     # 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 traversaldef reverseLevelOrder(root):    h = height(root)    for i in reversed(range(1, h+1)):        printGivenLevel(root,i) # Print nodes at a given leveldef printGivenLevel(root, level):     if root is None:        return    if level ==1 :        print root.data,     elif 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 nodedef height(node):    if node is None:        return 0    else:         # Compute the height of each subtree        lheight = height(node.left)        rheight = height(node.right)         # Use the larger one        if lheight > rheight :            return lheight + 1        else:            return rheight + 1 # Driver program to test above functionroot = 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)
// A recursive C# program to print// reverse level order traversalusing System; // A binary tree nodeclass Node{    public int data;    public Node left, right;             public Node(int item)    {        data = item;        left = right;    }}     class BinaryTree{Node root; /* Function to print REVERSElevel order traversal a tree*/void reverseLevelOrder(Node node){    int h = height(node);    int i;    for (i = h; i >= 1; i--)         // THE ONLY LINE DIFFERENT    // FROM NORMAL LEVEL ORDER    {        printGivenLevel(node, i);    }} /* Print nodes at a given level */void printGivenLevel(Node node, int level){    if (node == null)        return;    if (level == 1)        Console.Write(node.data + " ");    else if (level > 1)    {        printGivenLevel(node.left, level - 1);        printGivenLevel(node.right, level - 1);    }} /* Compute the "height" of a tree --the number of nodes along the longestpath from the root node down to thefarthest leaf node.*/int height(Node node){    if (node == null)        return 0;    else    {        /* compute the height of each subtree */        int lheight = height(node.left);        int rheight = height(node.right);         /* use the larger one */        if (lheight > rheight)            return (lheight + 1);        else            return (rheight + 1);    }} // Driver Codestatic public void Main(String []args){    BinaryTree tree = new BinaryTree();     // Let us create trees shown    // in above diagram    tree.root = new Node(1);    tree.root.left = new Node(2);    tree.root.right = new Node(3);    tree.root.left.left = new Node(4);    tree.root.left.right = new Node(5);             Console.WriteLine("Level Order traversal " +                        "of binary tree is : ");    tree.reverseLevelOrder(tree.root);}}     // This code is contributed// by Arnab Kundu
<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) {          var h = this.height(node);          var i;          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 + " ");          else if (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) return 0;          else {            /* compute the height of each subtree */            var lheight = this.height(node.left);            var rheight = this.height(node.right);             /* use the larger one */            if (lheight > rheight) return lheight + 1;            else return rheight + 1;          }        }      }      // Driver Code      var tree = new BinaryTree();       // Let us create trees shown      // in above diagram      tree.root = new Node(1);      tree.root.left = new Node(2);      tree.root.right = new Node(3);      tree.root.left.left = new Node(4);      tree.root.left.right = new Node(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: The worst-case time complexity of this method is O(n^2). For a skewed tree, printGivenLevel() takes O(n) time where n is the number of nodes in the skewed tree. So time complexity of printLevelOrder() is O(n) + O(n-1) + O(n-2) + .. + O(1) which is O(n^2).METHOD 2 (Using Queue and Stack) The method 2 of normal level order traversal can also be easily modified to print level order traversal in reverse order. The idea is to use a deque(double-ended queue) to get the reverse level order. A deque allows insertion and deletion at both the 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 children of a node in reverse order, we first push the right subtree to the deque, then process the left subtree. 
C++
Java
Python
C#
Javascript
// A C++ program to print REVERSE level order traversal using stack and queue// This approach is adopted from following link// http://tech-queries.blogspot.in/2008/12/level-order-tree-traversal-in-reverse.html#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left and right children */struct node{    int data;    struct node* left;    struct node* right;}; /* Given a binary tree, print its nodes in reverse level order */void reverseLevelOrder(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(int data){    node* temp = new node;    temp->data = data;    temp->left = NULL;    temp->right = NULL;     return (temp);} /* Driver program to test above functions*/int main(){    struct node *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);     return 0;}
// A recursive java program to print reverse level order traversal// using stack and queue  import java.util.LinkedList;import java.util.Queue;import java.util.Stack;  /* A binary tree node has data, pointer to left and right children */class Node{    int data;    Node left, right;      Node(int item)    {        data = item;        left = right;    }}  class BinaryTree{    Node root;      /* Given a binary tree, print its nodes in reverse level order */    void reverseLevelOrder(Node node)    {        Stack<Node> S = new Stack();        Queue<Node> Q = new LinkedList();        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    public static void main(String args[])    {        BinaryTree tree = new BinaryTree();          // Let us create trees shown in above diagram        tree.root = new Node(1);        tree.root.left = new Node(2);        tree.root.right = new Node(3);        tree.root.left.left = new Node(4);        tree.root.left.right = new Node(5);        tree.root.right.left = new Node(6);        tree.root.right.right = new Node(7);          System.out.println("Level Order traversal of binary tree is :");        tree.reverseLevelOrder(tree.root);      }}  // This code has been contributed by Mayank Jaiswal
# Python program to print REVERSE level order traversal using# stack and queue from collections import deque# A binary tree nodeclass Node:     # 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  def reverseLevelOrder(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()    while q:        node = q.popleft()        if node is None:            continue                 ans.appendleft(node.data)                 if node.right:            q.append(node.right)                     if node.left:            q.append(node.left)                 return ans # Driver program to test above functionroot = 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"reverseLevelOrder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
// A recursive C# program to print reverse// level order traversal using stack and queueusing System.Collections.Generic;using System; /* A binary tree node has data,pointer to left and right children */public class Node{    public int data;    public Node left, right;     public Node(int item)    {        data = item;        left = right;    }} public class BinaryTree{    Node root;     /* Given a binary tree, print its    nodes in reverse level order */    void reverseLevelOrder(Node node)    {        Stack<Node> S = new Stack<Node>();        Queue<Node> Q = new Queue<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    public static void Main()    {        BinaryTree tree = new BinaryTree();         // Let us create trees shown in above diagram        tree.root = new Node(1);        tree.root.left = new Node(2);        tree.root.right = new Node(3);        tree.root.left.left = new Node(4);        tree.root.left.right = new Node(5);        tree.root.right.left = new Node(6);        tree.root.right.right = new Node(7);         Console.WriteLine("Level Order traversal of binary tree is :");        tree.reverseLevelOrder(tree.root);     }} /* This code contributed by PrinciRaj1992 */
<script> // A recursive javascript program to print// reverse level order traversal// using stack and queue /* A binary tree node has data, pointer to leftand 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 */function reverseLevelOrder(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 diagramroot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.left = new Node(6);root.right.right = new Node(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.  
Reverse Level Order Traversal | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersReverse Level Order Traversal | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:58•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=FfF0FubRtYs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk 
Please write comments if you find any bug in the above programs/algorithms or other ways to solve the same problem.
andrew1234
rathbhupendra
princiraj1992
akashgkrishnan
rdtank
avanitrachhadiya2155
clintra
sayali31889
Adobe
Amazon
FactSet
Flipkart
Microsoft
Reverse
Tree
Flipkart
Amazon
Microsoft
FactSet
Adobe
Tree
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Introduction to Tree Data Structure
What is Data Structure: Types, Classifications and Applications
Binary Tree | Set 3 (Types of Binary Tree)
A program to check if a binary tree is BST or not
Binary Tree | Set 2 (Properties)
Diameter of a Binary Tree
Lowest Common Ancestor in a Binary Tree | Set 1
Decision Tree
Diagonal Traversal of Binary Tree