Reverse Level Order Traversal

Last Updated : 26 Aug, 2026

Given a binary tree, find its reverse level order traversal. i.e.,  the traversal begins from the last level.

Examples:

Input: root = [1, 3, 2]

2681

Output: [3, 2, 1]
Explanation: Traversing level 1 : 3 2, Traversing level 0 : 1

Input: root = [10, 20, 30, 40, 60]

2682

Output: [40, 60, 20, 30, 10]
Explanation: Traversing level 2 : 40 60, Traversing level 1 : 20 30, Traversing level 0 : 10

Try It Yourself
redirect icon

[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>
using namespace std;

/* Structure of Tree Node */
class Node
{
  public:
    int data;
    Node *left;
    Node *right;

    Node(int val)
    {
        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)
        return result;

    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.
        int size = q.size();

        vector<int> currentLevel;

        // Process all nodes of the current level.
        for (int i = 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 (int i = levels.size() - 1; i >= 0; i--)
    {
        for (int value : levels[i])
        {
            result.push_back(value);
        }
    }

    return result;
}

int main()
{
    /*
            1
           / \
          2   3
         / \
        4   5
    */

    Node *root = 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);
    
    vector<int> result = reverseLevelOrder(root);

    for (int x : result)
        cout << x << " ";

    return 0;
}
Java
import java.util.*;

/* Structure of Tree Node */
class Node {
    int data;
    Node left;
    Node right;

    Node(int val)
    {
        data = val;
        left = right = null;
    }
}

class GFG {
    static List<Integer> reverseLevelOrder(Node root)
    {
        List<Integer> result = new ArrayList<>();

        // If the tree is empty, return an empty result.
        if (root == null)
            return result;

        Queue<Node> q = new LinkedList<>();

        // Store each level separately.
        List<List<Integer> > levels = new ArrayList<>();

        // Start BFS traversal from the root.
        q.add(root);

        while (!q.isEmpty()) {
            // Number of nodes present at the current level.
            int size = q.size();

            List<Integer> currentLevel = new ArrayList<>();

            // Process all nodes of the current level.
            for (int i = 0; i < size; i++) {
                Node curr = 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 (int i = levels.size() - 1; i >= 0; i--) {
            for (int value : levels.get(i)) {
                result.add(value);
            }
        }

        return result;
    }

    public static void main(String[] args)
    {
        /*
                1
               / \
              2   3
             / \
            4   5
        */

        Node root = 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);

        List<Integer> result = reverseLevelOrder(root);

        for (int x : result)
            System.out.print(x + " ");
    }
}
Python
from collections import deque


# Structure of Tree Node
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None


def reverseLevelOrder(root):
    result = []

    # If the tree is empty, return an empty result.
    if root is None:
        return result

    q = deque()

    # Store each level separately.
    levels = []

    # Start BFS traversal from the root.
    q.append(root)

    while q:
        # Number of nodes present at the current level.
        size = len(q)

        currentLevel = []

        # Process all nodes of the current level.
        for i in range(size):
            curr = q.popleft()

            # Store the current node's value.
            currentLevel.append(curr.data)

            # Push the left child first.
            if curr.left is not None:
                q.append(curr.left)

            # Push the right child.
            if curr.right is not None:
                q.append(curr.right)

        # Store the current level.
        levels.append(currentLevel)

    # Traverse the levels from bottom to top.
    for i in range(len(levels) - 1, -1, -1):
        for value in levels[i]:
            result.append(value)

    return result


# Driver Code
if __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)

    for x in result:
        print(x, end=" ")
C#
using System;
using System.Collections.Generic;

/* Structure of Tree Node */
class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int val)
    {
        data = val;
        left = right = null;
    }
}

class GFG {
    static List<int> reverseLevelOrder(Node root)
    {
        List<int> result = new List<int>();

        // If the tree is empty, return an empty result.
        if (root == null)
            return result;

        Queue<Node> q = new Queue<Node>();

        // Store each level separately.
        List<List<int> > levels = new List<List<int> >();

        // Start BFS traversal from the root.
        q.Enqueue(root);

        while (q.Count > 0) {
            // Number of nodes present at the current level.
            int size = q.Count;

            List<int> currentLevel = new List<int>();

            // Process all nodes of the current level.
            for (int i = 0; i < size; i++) {
                Node curr = 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 (int i = levels.Count - 1; i >= 0; i--) {
            foreach(int value in levels[i])
            {
                result.Add(value);
            }
        }

        return result;
    }

    static void Main()
    {
        /*
                1
               / \
              2   3
             / \
            4   5
        */

        Node root = 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);

        List<int> result = reverseLevelOrder(root);

        foreach(int x in result) Console.Write(x + " ");
    }
}
JavaScript
/* Structure of Tree Node */
class Node {
    constructor(val)
    {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}


function reverseLevelOrder(root)
{
    let result = [];

    // If the tree is empty, return an empty result.
    if (root === null)
        return result;

    let q = [];
    let front = 0;

    // Store each level separately.
    let levels = [];

    // Start BFS traversal from the root.
    q.push(root);

    while (front < q.length) {
        // Number of nodes present at the current level.
        let size = q.length - front;

        let currentLevel = [];

        // Process all nodes of the current level.
        for (let i = 0; i < size; i++) {
            let curr = 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 (let i = levels.length - 1; i >= 0; i--) {
        for (let value of levels[i]) {
            result.push(value);
        }
    }

    return result;
}

// Driver Code
/*
           1
          / \
         2   3
        / \
       4   5
   */

let root = 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);

let result = 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>
using namespace std;

/* Structure of Tree Node */
class Node
{
  public:
    int data;
    Node *left;
    Node *right;

    Node(int val)
    {
        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)
        return result;

    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);
    }

    return result;
}

int main()
{
    /*
            1
           / \
          2   3
         / \
        4   5
    */

    Node *root = 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);

    vector<int> result = reverseLevelOrder(root);

    for (int x : result)
        cout << x << " ";

    return 0;
}
Java
import java.util.*;

/* Structure of Tree Node */
class Node {
    int data;
    Node left;
    Node right;

    Node(int val)
    {
        data = val;
        left = right = null;
    }
}

class GFG {
    static List<Integer> reverseLevelOrder(Node root)
    {
        List<Integer> result = new ArrayList<>();

        // If the tree is empty, return an empty result.
        if (root == null)
            return result;

        Queue<Node> q = new LinkedList<>();
        Stack<Node> st = new Stack<>();

        // Start BFS traversal from the root.
        q.add(root);

        while (!q.isEmpty()) {
            // Remove the front node from the queue.
            Node curr = 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()) {
            Node curr = st.pop();

            // Store the current node's value.
            result.add(curr.data);
        }

        return result;
    }

    public static void main(String[] args)
    {
        /*
                1
               / \
              2   3
             / \
            4   5
        */

        Node root = 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);

        List<Integer> result = reverseLevelOrder(root);

        for (int x : result)
            System.out.print(x + " ");
    }
}
Python
from collections import deque


# Structure of Tree Node
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None


def reverseLevelOrder(root):
    result = []

    # If the tree is empty, return an empty result.
    if root is None:
        return result

    q = deque()
    st = []

    # Start BFS traversal from the root.
    q.append(root)

    while q:
        # 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.
        if curr.right is not None:
            q.append(curr.right)

        # Push the left child after the right child.
        if curr.left is not None:
            q.append(curr.left)

    # Pop nodes from the stack to get
    # reverse level order traversal.
    while st:
        curr = st.pop()

        # Store the current node's value.
        result.append(curr.data)

    return result


# Driver Code
if __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)

    for x in result:
        print(x, end=" ")
C#
using System;
using System.Collections.Generic;

/* Structure of Tree Node */
class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int val)
    {
        data = val;
        left = right = null;
    }
}

class GFG {
    static List<int> reverseLevelOrder(Node root)
    {
        List<int> result = new List<int>();

        // If the tree is empty, return an empty result.
        if (root == null)
            return result;

        Queue<Node> q = new Queue<Node>();
        Stack<Node> st = new Stack<Node>();

        // Start BFS traversal from the root.
        q.Enqueue(root);

        while (q.Count > 0) {
            
            // Remove the front node from the queue.
            Node curr = 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) {
            Node curr = st.Pop();

            // Store the current node's value.
            result.Add(curr.data);
        }

        return result;
    }

    static void Main()
    {
        /*
                1
               / \
              2   3
             / \
            4   5
        */

        Node root = 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);

        List<int> result = reverseLevelOrder(root);

        foreach(int x in result) Console.Write(x + " ");
    }
}
JavaScript
/* Structure of Tree Node */
class Node {
    constructor(val)
    {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

function reverseLevelOrder(root)
{
    let result = [];

    // If the tree is empty, return an empty result.
    if (root === null)
        return result;

    let q = [];
    let st = [];
    let front = 0;

    // Start BFS traversal from the root.
    q.push(root);

    while (front < q.length) {
        // Remove the front node from the queue.
        let curr = 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) {
        let curr = st.pop();

        // Store the current node's value.
        result.push(curr.data);
    }

    return result;
}

// Driver Code

/*
            1
           / \
          2   3
         / \
        4   5
    */

let root = 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);

let result = reverseLevelOrder(root);

let res = ""
for (let x of result){
    res += x + " ";
}

console.log(res);

Output
4 5 2 3 1 
Comment