Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Queue
  • Practice Queue
  • MCQs on Queue
  • Queue Tutorial
  • Operations
  • Applications
  • Implementation
  • Stack vs Queue
  • Types of Queue
  • Circular Queue
  • Deque
  • Priority Queue
  • Stack using Queue
  • Advantages & Disadvantages
Open In App
Next Article:
Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
Next article icon

Print Binary Tree levels in sorted order

Last Updated : 29 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary tree, the task is to print its all level in sorted order Examples:

Input :     7
/ \
6 5
/ \ / \
4 3 2 1
Output :
7
5 6
1 2 3 4
Input : 7
/ \
16 1
/ \
4 13
Output :
7
1 16
4 13

Recommended Practice
Print Binary Tree levels in sorted order
Try It!

Here we can use two Priority queue for print in sorted order. We create an empty queue q and two priority queues, current_level and next_level. We use NULL as a separator between two levels. Whenever we encounter NULL in normal level order traversal, we swap current_level and next_level. 

CPP




// CPP program to print levels in sorted order.
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
  
// A Binary Tree Node
struct Node {
    int data;
    struct Node *left, *right;
};
  
// Iterative method to find height of Binary Tree
void printLevelOrder(Node* root)
{
    // Base Case
    if (root == NULL)
        return;
  
    // Create an empty queue for level order traversal
    queue<Node*> q;
  
    // A priority queue (or min heap) of integers for 
    // to store all elements of current level. 
    priority_queue<int, vector<int>, greater<int> > current_level;
  
    // A priority queue (or min heap) of integers for 
    // to store all elements of next level. 
    priority_queue<int, vector<int>, greater<int> > next_level;
  
    // push the root for traverse all next level nodes
    q.push(root);
  
    // for go level by level
    q.push(NULL);
  
    // push the first node data in previous_level queue
    current_level.push(root->data);
  
    while (q.empty() == false) {
  
        // Get top of priority queue 
        int data = current_level.top();
  
        // Get top of queue
        Node* node = q.front();
  
        // if node == NULL (Means this is boundary
        // between two levels), swap current_level
        // next_level priority queues.
        if (node == NULL) {
            q.pop();
  
            // here queue is empty represent
            // no element in the actual
            // queue
            if (q.empty())
                break;
  
            q.push(NULL);
            cout << "\n";
  
            // swap next_level to current_level level
            // for print in sorted order
            current_level.swap(next_level);
  
            continue;
        }
  
        // print the current_level data
        cout << data << " ";
  
        q.pop();
        current_level.pop();
  
        /* Enqueue left child */
        if (node->left != NULL) {
            q.push(node->left);
  
            // Enqueue left child in next_level queue
            next_level.push(node->left->data);
        }
  
        /*Enqueue right child */
        if (node->right != NULL) {
            q.push(node->right);
  
            // Enqueue right child in next_level queue
            next_level.push(node->right->data);
        }
    }
}
  
// Utility function to create a new tree node
Node* newNode(int data)
{
    Node* temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
  
// Driver program to test above functions
int main()
{
    // Let us create binary tree shown in above diagram
    Node* root = newNode(7);
    root->left = newNode(6);
    root->right = newNode(5);
    root->left->left = newNode(4);
    root->left->right = newNode(3);
    root->right->left = newNode(2);
    root->right->right = newNode(1);
  
    /*     7
         /    \
        6       5
       / \     / \
      4  3     2  1          */
  
    cout << "Level Order traversal of binary tree is \n";
    printLevelOrder(root);
    return 0;
}
 
 

Java




import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
  
// A Binary Tree Node
class Node {
    int data;
    Node left, right;
  
    public Node(int data) {
        this.data = data;
        this.left = this.right = null;
    }
}
  
public class BinaryTreeLevelOrder {
    // Iterative method to find height of Binary Tree
    public static void printLevelOrder(Node root) {
        // Base Case
        if (root == null) {
            return;
        }
  
        // Create an empty queue for level order traversal
        Queue<Node> queue = new LinkedList<>();
  
        // push the root to traverse all next level nodes
        queue.add(root);
  
        while (!queue.isEmpty()) {
            // Get the number of nodes at the current level
            int levelSize = queue.size();
  
            // A min heap to store elements of the current level
            PriorityQueue<Integer> currentLevel = new PriorityQueue<>();
  
            for (int i = 0; i < levelSize; i++) {
                // Get front of queue
                Node node = queue.poll();
  
                // Print the data of the current_level
                currentLevel.add(node.data);
  
                // Enqueue left child
                if (node.left != null) {
                    queue.add(node.left);
                }
  
                // Enqueue right child
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
  
            // Print elements of the current level in sorted order
            while (!currentLevel.isEmpty()) {
                System.out.print(currentLevel.poll() + " ");
            }
  
            System.out.println();
        }
    }
  
    // Utility function to create a new tree node
    public static Node newNode(int data) {
        return new Node(data);
    }
  
    // Driver program to test above functions
    public static void main(String[] args) {
        // Let us create a binary tree shown in the above diagram
        Node root = newNode(7);
        root.left = newNode(6);
        root.right = newNode(5);
        root.left.left = newNode(4);
        root.left.right = newNode(3);
        root.right.left = newNode(2);
        root.right.right = newNode(1);
  
        /*
                7
               / \
              6   5
             / \ / \
            4  3 2  1
        */
  
        System.out.println("Level Order traversal of binary tree in sorted order is ");
        printLevelOrder(root);
    }
}
 
 

Python3




import queue
import heapq
  
# A Binary Tree Node
class Node:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
  
# Iterative method to find height of Binary Tree
def printLevelOrder(root):
    # Base Case
    if root is None:
        return
  
    # Create an empty queue for level order traversal
    q = queue.Queue()
  
    # push the root to traverse all next level nodes
    q.put(root)
  
    while not q.empty():
        # Get the number of nodes at the current level
        level_size = q.qsize()
  
        # A min heap to store elements of the current level
        current_level = []
  
        for _ in range(level_size):
            # Get top of queue
            node = q.get()
  
            # print the current_level data
            heapq.heappush(current_level, node.data)
  
            # Enqueue left child
            if node.left is not None:
                q.put(node.left)
  
            # Enqueue right child
            if node.right is not None:
                q.put(node.right)
  
        # Print elements of the current level in sorted order
        while current_level:
            print(heapq.heappop(current_level), end=" ")
  
        print("")
  
# Utility function to create a new tree node
def newNode(data):
    temp = Node(data)
    return temp
  
# Driver program to test above functions
if __name__ == "__main__":
    # Let us create binary tree shown in the above diagram
    root = newNode(7)
    root.left = newNode(6)
    root.right = newNode(5)
    root.left.left = newNode(4)
    root.left.right = newNode(3)
    root.right.left = newNode(2)
    root.right.right = newNode(1)
  
    """
        7
       / \
      6   5
     / \ / \
    4  3 2  1
    """
  
    print("Level Order traversal of binary tree in sorted order is ")
    printLevelOrder(root)
 
 

C#




using System;
using System.Collections.Generic;
  
// A Binary Tree Node
public class Node
{
    public int Data;
    public Node Left, Right;
  
    public Node(int data)
    {
        this.Data = data;
        this.Left = this.Right = null;
    }
}
  
public class BinaryTreeLevelOrder
{
    // Iterative method to find the height of a Binary Tree
    public static void PrintLevelOrder(Node root)
    {
        // Base Case
        if (root == null)
        {
            return;
        }
  
        // Create an empty queue for level order traversal
        Queue<Node> queue = new Queue<Node>();
  
        // Enqueue the root to traverse all next level nodes
        queue.Enqueue(root);
  
        while (queue.Count > 0)
        {
            // Get the number of nodes at the current level
            int levelSize = queue.Count;
  
            // A sorted set to store elements of the current level
            SortedSet<int> currentLevel = new SortedSet<int>();
  
            for (int i = 0; i < levelSize; i++)
            {
                // Get the front of the queue
                Node node = queue.Dequeue();
  
                // Print the data of the current level
                currentLevel.Add(node.Data);
  
                // Enqueue the left child
                if (node.Left != null)
                {
                    queue.Enqueue(node.Left);
                }
  
                // Enqueue the right child
                if (node.Right != null)
                {
                    queue.Enqueue(node.Right);
                }
            }
  
            // Print elements of the current level in sorted order
            foreach (var item in currentLevel)
            {
                Console.Write(item + " ");
            }
  
            Console.WriteLine();
        }
    }
  
    // Utility function to create a new tree node
    public static Node NewNode(int data)
    {
        return new Node(data);
    }
  
    // Driver program to test above functions
    public static void Main(string[] args)
    {
        // Let us create a binary tree shown in the above diagram
        Node root = NewNode(7);
        root.Left = NewNode(6);
        root.Right = NewNode(5);
        root.Left.Left = NewNode(4);
        root.Left.Right = NewNode(3);
        root.Right.Left = NewNode(2);
        root.Right.Right = NewNode(1);
  
        /*
                7
               / \
              6   5
             / \ / \
            4  3 2  1
        */
  
        Console.WriteLine("Level Order traversal of binary tree in sorted order is ");
        PrintLevelOrder(root);
    }
}
 
 

Javascript




// Binary Tree Node
class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
  
// Iterative method to find height of Binary Tree
function printLevelOrder(root) {
    // Base Case
    if (root === null) {
        return;
    }
  
    // Create an empty queue for level order traversal
    let q = [];
  
    // push the root to traverse all next level nodes
    q.push(root);
  
    while (q.length !== 0) {
        // Get the number of nodes at the current level
        let levelSize = q.length;
  
        // A min heap to store elements of the current level
        let currentLevel = [];
  
        for (let i = 0; i < levelSize; i++) {
            // Get front of queue
            let node = q.shift();
  
            // Push the current node data to currentLevel array
            currentLevel.push(node.data);
  
            // Enqueue left child
            if (node.left !== null) {
                q.push(node.left);
            }
  
            // Enqueue right child
            if (node.right !== null) {
                q.push(node.right);
            }
        }
  
        // Print elements of the current level in sorted order
        currentLevel.sort((a, b) => a - b);
        console.log(currentLevel.join(" "));
    }
}
  
// Utility function to create a new tree node
function newNode(data) {
    let temp = new Node(data);
    return temp;
}
  
// Driver program to test above functions
// Let us create a binary tree
let root = newNode(7);
root.left = newNode(6);
root.right = newNode(5);
root.left.left = newNode(4);
root.left.right = newNode(3);
root.right.left = newNode(2);
root.right.right = newNode(1);
  
/*
        7
       / \
      6   5
     / \ / \
    4  3 2  1
*/
  
console.log("Level Order traversal of binary tree in sorted order is:");
printLevelOrder(root);
 
 
Output
Level Order traversal of binary tree is   7   5 6   1 2 3 4            

Time Complexity: O(n*log(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.



Next Article
Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
author
devanshuagarwal
Improve
Article Tags :
  • DSA
  • Queue
  • Sorting
  • Tree
  • cpp-priority-queue
  • priority-queue
  • tree-level-order
Practice Tags :
  • priority-queue
  • Queue
  • Sorting
  • Tree

Similar Reads

  • Print Binary Tree levels in sorted order | Set 2 (Using set)
    Given a tree, print the level order traversal in sorted order. Examples : Input : 7 / \ 6 5 / \ / \ 4 3 2 1 Output : 7 5 6 1 2 3 4 Input : 7 / \ 16 1 / \ 4 13 Output : 7 1 16 4 13 We have discussed a priority queue based solution in below post.Print Binary Tree levels in sorted order | Set 1 (Using
    5 min read
  • All Leaves of a Bnary Tree - Print in Order
    Given a binary tree, we need to print all leaf nodes of the given binary tree from left to right. That is, the nodes should be printed in the order they appear from left to right in the given tree.  For Example,  Input : Root of the below tree Output : 4 6 7 9 10 Corner Cases : For a tree with singl
    11 min read
  • Print Levels of all nodes in a Binary Tree
    Given a Binary Tree and a key, write a function that prints levels of all keys in given binary tree. For example, consider the following tree. If the input key is 3, then your function should return 1. If the input key is 4, then your function should return 3. And for key which is not present in key
    7 min read
  • Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
    Given a Complete Binary Tree as an array, the task is to print all of its levels in sorted order.Examples: Input: arr[] = {7, 6, 5, 4, 3, 2, 1} The given tree looks like 7 / \ 6 5 / \ / \ 4 3 2 1 Output: 7 5 6 1 2 3 4 Input: arr[] = {5, 6, 4, 9, 2, 1} The given tree looks like 5 / \ 6 4 / \ / 9 2 1
    6 min read
  • Level of a Node in Binary Tree
    Given a Binary Tree and a key, the task is to find the level of key in the Binary Tree. Examples: Input : key = 4 Output: 3Explanation: The level of the key in above binary tree is 3.Input : key = 10 Output: -1Explanation: Key is not present in the above Binary tree. Table of Content [Expected Appro
    12 min read
  • Level Order Predecessor of a node in Binary Tree
    Given a binary tree and a node in the binary tree, find Levelorder Predecessor of the given node. That is, the node that appears before the given node in the level order traversal of the tree. Note: The task is not just to print the data of the node, you have to return the complete node from the tre
    9 min read
  • Print all K-sum levels in a Binary Tree
    Given a Binary Tree and an integer K where the tree has positive and negative nodes, the task is to print the elements of the level whose sum equals K. If no such result exists, then print "Not Possible". Examples: Input: -10 / \ 2 -3 / \ \ 4 15 -6 / \ / 7 -8 9 K = 13 Output: 4 15 -6 Explanation: Le
    8 min read
  • Print all Nodes of given Binary Tree at the Kth Level
    Given a binary tree and an integer K, the task is to print all the integers at the Kth level in the tree from left to right. Examples: Input: Tree in the image below, K = 3 Output: 4 5 6Explanation: All the nodes present in level 3 of above binary tree from left to right are 4, 5, and 6. Input: Tree
    5 min read
  • Print all Prime Levels of a Binary Tree
    Given a Binary Tree, the task is to print all prime levels of this tree. Any level of a Binary tree is said to be a prime level, if all nodes of this level are prime. Examples: Input: 1 / \ 15 13 / / \ 11 7 29 \ / 2 3 Output: 11 7 29 2 3 Explanation: Third and Fourth levels are prime levels. Input:
    14 min read
  • Level Order Successor of a node in Binary Tree
    Given a binary tree and a node in the binary tree, find Levelorder successor of the given node. That is, the node that appears after the given node in the level order traversal of the tree. Note: The task is not just to print the data of the node, you have to return the complete node from the tree.
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences