Open In App

Print Binary Tree levels in sorted order

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
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

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.



Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads