Given an array arr[] which contains data of n nodes of Complete Binary tree in level order fashion. The task is to print the level order traversal in sorted order.
Examples:
Input : arr[] = [7 6 5 4 3 2 1] Output : [[7],[5,6],[1,2,3,4]] Explanation: The formed Binary Tree is:
Input: arr[] = [7,16,14,13] Output: [[7],[1,16],[4,13]] Explanation: The formed Binary Tree is:
[Naive Approach] Level Order with Sorting - O(n log n) Time and O(n) Space
Build a complete binary tree from the given level-order array, then perform level order traversal. For each level, extract all node values, sort them, and store in result.
Build complete binary tree using recursion with index formula: left = 2*i + 1, right = 2*i + 2.
Perform level order traversal using queue.
For each level, collect all node values in currentLevel vector.
Sort currentLevel and push to sortedLevels.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intvalue){data=value;left=nullptr;right=nullptr;}};// Builds a complete binary tree from the level-order arrayNode*buildTree(vector<int>&arr,intindex){// If index goes outside the array,// there is no node to createif(index>=arr.size()){returnnullptr;}// Create the current nodeNode*root=newNode(arr[index]);// Build left and right subtreesroot->left=buildTree(arr,2*index+1);root->right=buildTree(arr,2*index+2);returnroot;}vector<vector<int>>levelSort(vector<int>&arr){vector<vector<int>>sortedLevels;// Construct the complete binary treeNode*root=buildTree(arr,0);if(root==nullptr){returnsortedLevels;}queue<Node*>q;q.push(root);// Standard level-order traversalwhile(!q.empty()){intlevelSize=q.size();vector<int>currentLevel;// Process all nodes of the current levelfor(inti=0;i<levelSize;i++){Node*currentNode=q.front();q.pop();currentLevel.push_back(currentNode->data);if(currentNode->left){q.push(currentNode->left);}if(currentNode->right){q.push(currentNode->right);}}// Sort the nodes present in this levelsort(currentLevel.begin(),currentLevel.end());sortedLevels.push_back(currentLevel);}returnsortedLevels;}intmain(){vector<int>arr={7,6,5,4,3,2,1};vector<vector<int>>result=levelSort(arr);// Print level by levelfor(auto&level:result){for(intvalue:level){cout<<value<<" ";}cout<<endl;}return0;}
Java
// Java program to get level-wise sorted values of a binary treeimportjava.util.*;classNode{intdata;Nodeleft;Noderight;Node(intvalue){data=value;left=null;right=null;}}classGfG{// Builds a complete binary tree from the level-order arraystaticNodebuildTree(int[]arr,intindex){// If index goes outside the array, there is no node to createif(index>=arr.length){returnnull;}// Create the current nodeNoderoot=newNode(arr[index]);// Build left and right subtreesroot.left=buildTree(arr,2*index+1);root.right=buildTree(arr,2*index+2);returnroot;}staticList<List<Integer>>levelSort(int[]arr){List<List<Integer>>sortedLevels=newArrayList<>();// Construct the complete binary treeNoderoot=buildTree(arr,0);if(root==null){returnsortedLevels;}Queue<Node>q=newLinkedList<>();q.add(root);// Standard level-order traversalwhile(!q.isEmpty()){intlevelSize=q.size();List<Integer>currentLevel=newArrayList<>();// Process all nodes of the current levelfor(inti=0;i<levelSize;i++){NodecurrentNode=q.poll();currentLevel.add(currentNode.data);if(currentNode.left!=null){q.add(currentNode.left);}if(currentNode.right!=null){q.add(currentNode.right);}}// Sort the nodes present in this levelCollections.sort(currentLevel);sortedLevels.add(currentLevel);}returnsortedLevels;}publicstaticvoidmain(String[]args){int[]arr={7,6,5,4,3,2,1};List<List<Integer>>result=levelSort(arr);// Print level by levelfor(List<Integer>level:result){for(intvalue:level){System.out.print(value+" ");}System.out.println();}}}
Python
# Python program to get level-wise sorted values of a binary treefromcollectionsimportdequeclassNode:def__init__(self,value):self.data=valueself.left=Noneself.right=None# Builds a complete binary tree from the level-order arraydefbuildTree(arr,index):# If index goes outside the array, there is no node to createifindex>=len(arr):returnNone# Create the current noderoot=Node(arr[index])# Build left and right subtreesroot.left=buildTree(arr,2*index+1)root.right=buildTree(arr,2*index+2)returnrootdeflevelSort(arr):sortedLevels=[]# Construct the complete binary treeroot=buildTree(arr,0)ifrootisNone:returnsortedLevelsq=deque()q.append(root)# Standard level-order traversalwhileq:levelSize=len(q)currentLevel=[]# Process all nodes of the current levelfor_inrange(levelSize):currentNode=q.popleft()currentLevel.append(currentNode.data)ifcurrentNode.left:q.append(currentNode.left)ifcurrentNode.right:q.append(currentNode.right)# Sort the nodes present in this levelcurrentLevel.sort()sortedLevels.append(currentLevel)returnsortedLevels# Driver codeif__name__=="__main__":arr=[7,6,5,4,3,2,1]result=levelSort(arr)# Print level by levelforlevelinresult:print(' '.join(map(str,level)))
C#
// C# program to get level-wise sorted values of a binary treeusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intvalue){data=value;left=null;right=null;}}classGfG{// Builds a complete binary tree from the level-order arraystaticNodebuildTree(int[]arr,intindex){// If index goes outside the array, there is no node to createif(index>=arr.Length){returnnull;}// Create the current nodeNoderoot=newNode(arr[index]);// Build left and right subtreesroot.left=buildTree(arr,2*index+1);root.right=buildTree(arr,2*index+2);returnroot;}staticList<List<int>>levelSort(int[]arr){List<List<int>>sortedLevels=newList<List<int>>();// Construct the complete binary treeNoderoot=buildTree(arr,0);if(root==null){returnsortedLevels;}Queue<Node>q=newQueue<Node>();q.Enqueue(root);// Standard level-order traversalwhile(q.Count>0){intlevelSize=q.Count;List<int>currentLevel=newList<int>();// Process all nodes of the current levelfor(inti=0;i<levelSize;i++){NodecurrentNode=q.Dequeue();currentLevel.Add(currentNode.data);if(currentNode.left!=null){q.Enqueue(currentNode.left);}if(currentNode.right!=null){q.Enqueue(currentNode.right);}}// Sort the nodes present in this levelcurrentLevel.Sort();sortedLevels.Add(currentLevel);}returnsortedLevels;}staticvoidMain(string[]args){int[]arr={7,6,5,4,3,2,1};List<List<int>>result=levelSort(arr);// Print level by levelforeach(List<int>levelinresult){Console.WriteLine(string.Join(" ",level));}}}
JavaScript
// JavaScript program to get level-wise sorted values of a binary treeclassNode{constructor(value){this.data=value;this.left=null;this.right=null;}}// Builds a complete binary tree from the level-order arrayfunctionbuildTree(arr,index){// If index goes outside the array, there is no node to createif(index>=arr.length){returnnull;}// Create the current nodeletroot=newNode(arr[index]);// Build left and right subtreesroot.left=buildTree(arr,2*index+1);root.right=buildTree(arr,2*index+2);returnroot;}functionlevelSort(arr){letsortedLevels=[];// Construct the complete binary treeletroot=buildTree(arr,0);if(root===null){returnsortedLevels;}letqueue=[];queue.push(root);// Standard level-order traversalwhile(queue.length>0){letlevelSize=queue.length;letcurrentLevel=[];// Process all nodes of the current levelfor(leti=0;i<levelSize;i++){letcurrentNode=queue.shift();currentLevel.push(currentNode.data);if(currentNode.left){queue.push(currentNode.left);}if(currentNode.right){queue.push(currentNode.right);}}// Sort the nodes present in this levelcurrentLevel.sort((a,b)=>a-b);sortedLevels.push(currentLevel);}returnsortedLevels;}// Driver codeconstarr=[7,6,5,4,3,2,1];constresult=levelSort(arr);// Print level by levelfor(letlevelofresult){console.log(level.join(' '));}
Output
7
5 6
1 2 3 4
[Optimal Approach] Level-Based Partition and Sort - O(n log n) Time and O(n) Space
In a complete binary tree stored in level-order array, each level has 2^levelNumber nodes except possibly the last level. Partition the array into level segments without building the tree, sort each segment, and store in result.
C++
#include<bits/stdc++.h>usingnamespacestd;vector<vector<int>>levelSort(vector<int>&arr){// Stores the final sorted levelsvector<vector<int>>sortedLevels;// Points to the first element of the current levelintcurrentIndex=0;// Level numbering starts from 1intlevelNumber=1;// Process levels until all elements are coveredwhile(currentIndex<arr.size()){// Calculate the ending position of the current levelintlevelEnd=(1<<levelNumber)-1;// Make sure we do not go outside the arraylevelEnd=min(levelEnd,(int)arr.size());// Sort only the elements belonging to the current levelsort(arr.begin()+currentIndex,arr.begin()+levelEnd);vector<int>currentLevel;// Collect all sorted elements of this levelfor(inti=currentIndex;i<levelEnd;i++){currentLevel.push_back(arr[i]);}// Add the current level to the answersortedLevels.push_back(currentLevel);// Move to the next levelcurrentIndex=levelEnd;// Increase level numberlevelNumber++;}returnsortedLevels;}intmain(){vector<int>arr={7,6,5,4,3,2,1};vector<vector<int>>result=levelSort(arr);// Print all levelsfor(auto&level:result){for(intvalue:level){cout<<value<<" ";}cout<<endl;}return0;}
Java
// Java program to get level-wise sorted values of a binary treeimportjava.util.*;classGfG{staticList<List<Integer>>levelSort(List<Integer>arr){// Stores the final sorted levelsList<List<Integer>>sortedLevels=newArrayList<>();// Points to the first element of the current levelintcurrentIndex=0;// Level numbering starts from 1intlevelNumber=1;// Process levels until all elements are coveredwhile(currentIndex<arr.size()){// Calculate the ending position of the current levelintlevelEnd=(1<<levelNumber)-1;// Make sure we do not go outside the arraylevelEnd=Math.min(levelEnd,arr.size());// Sort only the elements belonging to the current levelCollections.sort(arr.subList(currentIndex,levelEnd));List<Integer>currentLevel=newArrayList<>();// Collect all sorted elements of this levelfor(inti=currentIndex;i<levelEnd;i++){currentLevel.add(arr.get(i));}// Add the current level to the answersortedLevels.add(currentLevel);// Move to the next levelcurrentIndex=levelEnd;// Increase level numberlevelNumber++;}returnsortedLevels;}publicstaticvoidmain(String[]args){List<Integer>arr=Arrays.asList(7,6,5,4,3,2,1);List<List<Integer>>result=levelSort(arr);// Print all levelsfor(List<Integer>level:result){for(intvalue:level){System.out.print(value+" ");}System.out.println();}}}
Python
# Python program to get level-wise sorted values of a binary treedeflevelSort(arr):# Stores the final sorted levelssortedLevels=[]# Points to the first element of the current levelcurrentIndex=0# Level numbering starts from 1levelNumber=1# Process levels until all elements are coveredwhilecurrentIndex<len(arr):# Calculate the ending position of the current levellevelEnd=(1<<levelNumber)-1# Make sure we do not go outside the arraylevelEnd=min(levelEnd,len(arr))# Sort only the elements belonging to the current levelarr[currentIndex:levelEnd]=sorted(arr[currentIndex:levelEnd])currentLevel=[]# Collect all sorted elements of this levelforiinrange(currentIndex,levelEnd):currentLevel.append(arr[i])# Add the current level to the answersortedLevels.append(currentLevel)# Move to the next levelcurrentIndex=levelEnd# Increase level numberlevelNumber+=1returnsortedLevels# Driver codeif__name__=="__main__":arr=[7,6,5,4,3,2,1]result=levelSort(arr)# Print all levelsforlevelinresult:print(' '.join(map(str,level)))
C#
// C# program to get level-wise sorted values of a binary treeusingSystem;usingSystem.Collections.Generic;usingSystem.Linq;classGfG{staticList<List<int>>levelSort(List<int>arr){// Stores the final sorted levelsList<List<int>>sortedLevels=newList<List<int>>();// Points to the first element of the current levelintcurrentIndex=0;// Level numbering starts from 1intlevelNumber=1;// Process levels until all elements are coveredwhile(currentIndex<arr.Count){// Calculate the ending position of the current levelintlevelEnd=(1<<levelNumber)-1;// Make sure we do not go outside the arraylevelEnd=Math.Min(levelEnd,arr.Count);// Sort only the elements belonging to the current levelList<int>subArray=arr.GetRange(currentIndex,levelEnd-currentIndex);subArray.Sort();for(inti=0;i<subArray.Count;i++){arr[currentIndex+i]=subArray[i];}List<int>currentLevel=newList<int>();// Collect all sorted elements of this levelfor(inti=currentIndex;i<levelEnd;i++){currentLevel.Add(arr[i]);}// Add the current level to the answersortedLevels.Add(currentLevel);// Move to the next levelcurrentIndex=levelEnd;// Increase level numberlevelNumber++;}returnsortedLevels;}staticvoidMain(string[]args){List<int>arr=newList<int>{7,6,5,4,3,2,1};List<List<int>>result=levelSort(arr);// Print all levelsforeach(List<int>levelinresult){Console.WriteLine(string.Join(" ",level));}}}
JavaScript
// JavaScript program to get level-wise sorted values of a binary treefunctionlevelSort(arr){// Stores the final sorted levelsletsortedLevels=[];// Points to the first element of the current levelletcurrentIndex=0;// Level numbering starts from 1letlevelNumber=1;// Process levels until all elements are coveredwhile(currentIndex<arr.length){// Calculate the ending position of the current levelletlevelEnd=(1<<levelNumber)-1;// Make sure we do not go outside the arraylevelEnd=Math.min(levelEnd,arr.length);// Get the current level elementsletcurrentLevelElements=arr.slice(currentIndex,levelEnd);// Sort the current level elementscurrentLevelElements.sort((a,b)=>a-b);// Update the original array with sorted valuesfor(leti=0;i<currentLevelElements.length;i++){arr[currentIndex+i]=currentLevelElements[i];}letcurrentLevel=[];// Collect all sorted elements of this levelfor(leti=currentIndex;i<levelEnd;i++){currentLevel.push(arr[i]);}// Add the current level to the answersortedLevels.push(currentLevel);// Move to the next levelcurrentIndex=levelEnd;// Increase level numberlevelNumber++;}returnsortedLevels;}// Driver codeletarr=[7,6,5,4,3,2,1];letresult=levelSort(arr);// Print all levelsfor(letlevelofresult){console.log(level.join(' '));}