Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
Last Updated :
11 Jul, 2025
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
Output:
5
4 6
1 2 9
Approach: A similar problem is discussed here
As the given tree is a Complete Binary Tree:
No. of nodes at a level l will be 2l where l ? 0
- Start traversing the array with level initialized as 0.
- Sort the elements which are the part of the current level and print the elements.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to print all the levels
// of the given tree in sorted order
void printSortedLevels(int arr[], int n)
{
// Initialize level with 0
int level = 0;
for (int i = 0; i < n; level++) {
// Number of nodes at current level
int cnt = (int)pow(2, level);
// Indexing of array starts from 0
// so subtract no. of nodes by 1
cnt -= 1;
// Index of the last node in the current level
int j = min(i + cnt, n - 1);
// Sort the nodes of the current level
sort(arr + i, arr + j + 1);
// Print the sorted nodes
while (i <= j) {
cout << arr[i] << " ";
i++;
}
cout << endl;
}
}
// Driver code
int main()
{
int arr[] = { 5, 6, 4, 9, 2, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
printSortedLevels(arr, n);
return 0;
}
Java
// Java implementation of the approach
import java.util.Arrays;
class GFG
{
// Function to print all the levels
// of the given tree in sorted order
static void printSortedLevels(int arr[], int n)
{
// Initialize level with 0
int level = 0;
for (int i = 0; i < n; level++)
{
// Number of nodes at current level
int cnt = (int)Math.pow(2, level);
// Indexing of array starts from 0
// so subtract no. of nodes by 1
cnt -= 1;
// Index of the last node in the current level
int j = Math.min(i + cnt, n - 1);
// Sort the nodes of the current level
Arrays.sort(arr, i, j+1);
// Print the sorted nodes
while (i <= j)
{
System.out.print(arr[i] + " ");
i++;
}
System.out.println();
}
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 5, 6, 4, 9, 2, 1 };
int n = arr.length;
printSortedLevels(arr, n);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation of the approach
from math import pow
# Function to print all the levels
# of the given tree in sorted order
def printSortedLevels(arr, n):
# Initialize level with 0
level = 0
i = 0
while(i < n):
# Number of nodes at current level
cnt = int(pow(2, level))
# Indexing of array starts from 0
# so subtract no. of nodes by 1
cnt -= 1
# Index of the last node in the current level
j = min(i + cnt, n - 1)
# Sort the nodes of the current level
arr = arr[:i] + sorted(arr[i:j + 1]) + \
arr[j + 1:]
# Print the sorted nodes
while (i <= j):
print(arr[i], end = " ")
i += 1
print()
level += 1
# Driver code
arr = [ 5, 6, 4, 9, 2, 1]
n = len(arr)
printSortedLevels(arr, n)
# This code is contributed by SHUBHAMSINGH10
C#
// C# implementation of the approach
using System;
using System.Linq;
class GFG
{
// Function to print all the levels
// of the given tree in sorted order
static void printSortedLevels(int []arr, int n)
{
// Initialize level with 0
int level = 0;
for (int i = 0; i < n; level++)
{
// Number of nodes at current level
int cnt = (int)Math.Pow(2, level);
// Indexing of array starts from 0
// so subtract no. of nodes by 1
cnt -= 1;
// Index of the last node in the current level
int j = Math.Min(i + cnt, n - 1);
// Sort the nodes of the current level
Array.Sort(arr, i, j + 1 - i);
// Print the sorted nodes
while (i <= j)
{
Console.Write(arr[i] + " ");
i++;
}
Console.WriteLine();
}
}
// Driver code
public static void Main(String[] args)
{
int []arr = { 5, 6, 4, 9, 2, 1 };
int n = arr.Length;
printSortedLevels(arr, n);
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript implementation of the approach
// Function to sort the elements of the array
// from index a to index b
function partSort(arr, N, a, b)
{
// Variables to store start and end of the index range
let l = Math.min(a, b);
let r = Math.max(a, b);
// Temporary array
let temp = new Array(r - l + 1);
temp.fill(0);
let j = 0;
for (let i = l; i <= r; i++) {
temp[j] = arr[i];
j++;
}
// Sort the temporary array
temp.sort(function(a, b){return a - b});
// Modifying original array with temporary array elements
j = 0;
for (let i = l; i <= r; i++) {
arr[i] = temp[j];
j++;
}
}
// Function to print all the levels
// of the given tree in sorted order
function printSortedLevels(arr, n)
{
// Initialize level with 0
let level = 0;
for (let i = 0; i < n; level++)
{
// Number of nodes at current level
let cnt = Math.pow(2, level);
// Indexing of array starts from 0
// so subtract no. of nodes by 1
cnt -= 1;
// Index of the last node in the current level
let j = Math.min(i + cnt, n - 1);
// Sort the nodes of the current level
partSort(arr, n, i, j + 1);
// Print the sorted nodes
while (i <= j)
{
document.write(arr[i] + " ");
i++;
}
document.write("</br>");
}
}
let arr = [ 5, 6, 4, 9, 2, 1 ];
let n = arr.length;
printSortedLevels(arr, n);
</script>
Time complexity: O(nlogn) where n is no of nodes in binary tree
Auxiliary space: O(1) as it is using constant space
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
Print Binary Tree levels in sorted order Given a Binary tree, the task is to print its all level in sorted order Examples: Input : 7 / \ 6 5 / \ / \ 4 3 2 1Output : 75 61 2 3 4 Input : 7 / \ 16 1 / \ 4 13 Output :7 1 164 13Recommended PracticePrint Binary Tree levels in sorted orderTry It!Here we can use two Priority queue for print in sor
9 min read
Check if the given array can represent Level Order Traversal of Binary Search Tree Given an array of size n. The task is to check whether the given array can represent the level order traversal of a Binary Search Tree or not.Examples: Input: arr[] = {7, 4, 12, 3, 6, 8, 1, 5, 10}Output: TrueExplanation: For the given arr[] the Binary Search Tree is: Input: arr[] = {11, 6, 13, 5, 12
9 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 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
All nodes between two given levels in Binary Tree Given a binary tree, the task is to print all nodes between two given levels in a binary tree. Print the nodes level-wise, i.e., the nodes for any level should be printed from left to right. Note: The levels are 1-indexed, i.e., root node is at level 1.Example: Input: Binary tree, l = 2, h = 3Output
8 min read