Print Binary Tree levels in sorted order
Last Updated :
29 Mar, 2024
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);
OutputLevel 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.
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 treeOutput : 4 6 7 9 10Corner Cases : For a tree with single no
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 = 4Output: 3Explanation: The level of the key in above binary tree is 3.Input : key = 10Output: -1Explanation: Key is not present in the above Binary tree.Table of Content[Expected Approach -
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
8 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