Open In App

Print Binary Tree levels in sorted order | Set 3 (Tree given as array)

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
5 Likes
Like
Report

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


 

  1. Start traversing the array with level initialized as 0.
  2. Sort the elements which are the part of the current level and print the elements.


Below is the implementation of the above approach: 
 

C++
Java Python3 C# JavaScript

Output: 
5 
4 6 
1 2 9

 

Time complexity: O(nlogn) where n is no of nodes in binary tree

Auxiliary space: O(1) as it is using constant space


Article Tags :

Explore