Traversing Complete Binary Tree Given as Array

Last Updated : 12 Jun, 2026

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:

split_array_into_three_equal_sum_segments_32

Input: arr[] = [7,16,14,13]
Output: [[7],[1,16],[4,13]]
Explanation: The formed Binary Tree is:

split_array_into_three_equal_sum_segments_33
Try It Yourself
redirect icon

[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>
using namespace std;

class Node
{
public:
    int data;
    Node* left;
    Node* right;

    Node(int value)
    {
        data = value;
        left = nullptr;
        right = nullptr;
    }
};

// Builds a complete binary tree from the level-order array
Node* buildTree(vector<int>& arr, int index)
{
    // If index goes outside the array,
    // there is no node to create
    if(index >= arr.size())
    {
        return nullptr;
    }

    // Create the current node
    Node* root = new Node(arr[index]);

    // Build left and right subtrees
    root->left = buildTree(arr, 2 * index + 1);
    root->right = buildTree(arr, 2 * index + 2);

    return root;
}

vector<vector<int>> levelSort(vector<int>& arr)
{
    vector<vector<int>> sortedLevels;

    // Construct the complete binary tree
    Node* root = buildTree(arr, 0);

    if(root == nullptr)
    {
        return sortedLevels;
    }

    queue<Node*> q;
    q.push(root);

    // Standard level-order traversal
    while(!q.empty())
    {
        int levelSize = q.size();

        vector<int> currentLevel;

        // Process all nodes of the current level
        for(int i = 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 level
        sort(currentLevel.begin(), currentLevel.end());

        sortedLevels.push_back(currentLevel);
    }

    return sortedLevels;
}

int main()
{
    vector<int> arr = {7, 6, 5, 4, 3, 2, 1};

    vector<vector<int>> result = levelSort(arr);

    // Print level by level
    for(auto &level : result)
    {
        for(int value : level)
        {
            cout << value << " ";
        }

        cout << endl;
    }

    return 0;
}
Java
// Java program to get level-wise sorted values of a binary tree
import java.util.*;

class Node {
    int data;
    Node left;
    Node right;
    
    Node(int value) {
        data = value;
        left = null;
        right = null;
    }
}

class GfG {
    
    // Builds a complete binary tree from the level-order array
    static Node buildTree(int[] arr, int index) {
        // If index goes outside the array, there is no node to create
        if (index >= arr.length) {
            return null;
        }
        
        // Create the current node
        Node root = new Node(arr[index]);
        
        // Build left and right subtrees
        root.left = buildTree(arr, 2 * index + 1);
        root.right = buildTree(arr, 2 * index + 2);
        
        return root;
    }
    
    static List<List<Integer>> levelSort(int[] arr) {
        List<List<Integer>> sortedLevels = new ArrayList<>();
        
        // Construct the complete binary tree
        Node root = buildTree(arr, 0);
        
        if (root == null) {
            return sortedLevels;
        }
        
        Queue<Node> q = new LinkedList<>();
        q.add(root);
        
        // Standard level-order traversal
        while (!q.isEmpty()) {
            int levelSize = q.size();
            List<Integer> currentLevel = new ArrayList<>();
            
            // Process all nodes of the current level
            for (int i = 0; i < levelSize; i++) {
                Node currentNode = 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 level
            Collections.sort(currentLevel);
            sortedLevels.add(currentLevel);
        }
        
        return sortedLevels;
    }
    
    public static void main(String[] args) {
        int[] arr = {7, 6, 5, 4, 3, 2, 1};
        
        List<List<Integer>> result = levelSort(arr);
        
        // Print level by level
        for (List<Integer> level : result) {
            for (int value : level) {
                System.out.print(value + " ");
            }
            System.out.println();
        }
    }
}
Python
# Python program to get level-wise sorted values of a binary tree
from collections import deque

class Node:
    def __init__(self, value):
        self.data = value
        self.left = None
        self.right = None

# Builds a complete binary tree from the level-order array
def buildTree(arr, index):
    # If index goes outside the array, there is no node to create
    if index >= len(arr):
        return None
    
    # Create the current node
    root = Node(arr[index])
    
    # Build left and right subtrees
    root.left = buildTree(arr, 2 * index + 1)
    root.right = buildTree(arr, 2 * index + 2)
    
    return root

def levelSort(arr):
    sortedLevels = []
    
    # Construct the complete binary tree
    root = buildTree(arr, 0)
    
    if root is None:
        return sortedLevels
    
    q = deque()
    q.append(root)
    
    # Standard level-order traversal
    while q:
        levelSize = len(q)
        currentLevel = []
        
        # Process all nodes of the current level
        for _ in range(levelSize):
            currentNode = q.popleft()
            currentLevel.append(currentNode.data)
            
            if currentNode.left:
                q.append(currentNode.left)
            
            if currentNode.right:
                q.append(currentNode.right)
        
        # Sort the nodes present in this level
        currentLevel.sort()
        sortedLevels.append(currentLevel)
    
    return sortedLevels

# Driver code
if __name__ == "__main__":
    arr = [7, 6, 5, 4, 3, 2, 1]
    
    result = levelSort(arr)
    
    # Print level by level
    for level in result:
        print(' '.join(map(str, level)))
C#
// C# program to get level-wise sorted values of a binary tree
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left;
    public Node right;
    
    public Node(int value) {
        data = value;
        left = null;
        right = null;
    }
}

class GfG {
    
    // Builds a complete binary tree from the level-order array
    static Node buildTree(int[] arr, int index) {
        // If index goes outside the array, there is no node to create
        if (index >= arr.Length) {
            return null;
        }
        
        // Create the current node
        Node root = new Node(arr[index]);
        
        // Build left and right subtrees
        root.left = buildTree(arr, 2 * index + 1);
        root.right = buildTree(arr, 2 * index + 2);
        
        return root;
    }
    
    static List<List<int>> levelSort(int[] arr) {
        List<List<int>> sortedLevels = new List<List<int>>();
        
        // Construct the complete binary tree
        Node root = buildTree(arr, 0);
        
        if (root == null) {
            return sortedLevels;
        }
        
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);
        
        // Standard level-order traversal
        while (q.Count > 0) {
            int levelSize = q.Count;
            List<int> currentLevel = new List<int>();
            
            // Process all nodes of the current level
            for (int i = 0; i < levelSize; i++) {
                Node currentNode = 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 level
            currentLevel.Sort();
            sortedLevels.Add(currentLevel);
        }
        
        return sortedLevels;
    }
    
    static void Main(string[] args) {
        int[] arr = {7, 6, 5, 4, 3, 2, 1};
        
        List<List<int>> result = levelSort(arr);
        
        // Print level by level
        foreach (List<int> level in result) {
            Console.WriteLine(string.Join(" ", level));
        }
    }
}
JavaScript
// JavaScript program to get level-wise sorted values of a binary tree

class Node {
    constructor(value) {
        this.data = value;
        this.left = null;
        this.right = null;
    }
}

// Builds a complete binary tree from the level-order array
function buildTree(arr, index) {
    // If index goes outside the array, there is no node to create
    if (index >= arr.length) {
        return null;
    }
    
    // Create the current node
    let root = new Node(arr[index]);
    
    // Build left and right subtrees
    root.left = buildTree(arr, 2 * index + 1);
    root.right = buildTree(arr, 2 * index + 2);
    
    return root;
}

function levelSort(arr) {
    let sortedLevels = [];
    
    // Construct the complete binary tree
    let root = buildTree(arr, 0);
    
    if (root === null) {
        return sortedLevels;
    }
    
    let queue = [];
    queue.push(root);
    
    // Standard level-order traversal
    while (queue.length > 0) {
        let levelSize = queue.length;
        let currentLevel = [];
        
        // Process all nodes of the current level
        for (let i = 0; i < levelSize; i++) {
            let currentNode = 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 level
        currentLevel.sort((a, b) => a - b);
        sortedLevels.push(currentLevel);
    }
    
    return sortedLevels;
}

// Driver code
const arr = [7, 6, 5, 4, 3, 2, 1];

const result = levelSort(arr);

// Print level by level
for (let level of result) {
    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>
using namespace std;

vector<vector<int>> levelSort(vector<int>& arr)
{
    // Stores the final sorted levels
    vector<vector<int>> sortedLevels;

    // Points to the first element of the current level
    int currentIndex = 0;

    // Level numbering starts from 1
    int levelNumber = 1;

    // Process levels until all elements are covered
    while(currentIndex < arr.size())
    {
        // Calculate the ending position of the current level
        int levelEnd = (1 << levelNumber) - 1;

        // Make sure we do not go outside the array
        levelEnd = min(levelEnd, (int)arr.size());

        // Sort only the elements belonging to the current level
        sort(arr.begin() + currentIndex,
             arr.begin() + levelEnd);

        vector<int> currentLevel;

        // Collect all sorted elements of this level
        for(int i = currentIndex; i < levelEnd; i++)
        {
            currentLevel.push_back(arr[i]);
        }

        // Add the current level to the answer
        sortedLevels.push_back(currentLevel);

        // Move to the next level
        currentIndex = levelEnd;

        // Increase level number
        levelNumber++;
    }

    return sortedLevels;
}

int main()
{
    vector<int> arr = {7, 6, 5, 4, 3, 2, 1};

    vector<vector<int>> result = levelSort(arr);

    // Print all levels
    for(auto &level : result)
    {
        for(int value : level)
        {
            cout << value << " ";
        }

        cout << endl;
    }

    return 0;
}
Java
// Java program to get level-wise sorted values of a binary tree
import java.util.*;

class GfG {
    
    static List<List<Integer>> levelSort(List<Integer> arr) {
        // Stores the final sorted levels
        List<List<Integer>> sortedLevels = new ArrayList<>();
        
        // Points to the first element of the current level
        int currentIndex = 0;
        
        // Level numbering starts from 1
        int levelNumber = 1;
        
        // Process levels until all elements are covered
        while (currentIndex < arr.size()) {
            // Calculate the ending position of the current level
            int levelEnd = (1 << levelNumber) - 1;
            
            // Make sure we do not go outside the array
            levelEnd = Math.min(levelEnd, arr.size());
            
            // Sort only the elements belonging to the current level
            Collections.sort(arr.subList(currentIndex, levelEnd));
            
            List<Integer> currentLevel = new ArrayList<>();
            
            // Collect all sorted elements of this level
            for (int i = currentIndex; i < levelEnd; i++) {
                currentLevel.add(arr.get(i));
            }
            
            // Add the current level to the answer
            sortedLevels.add(currentLevel);
            
            // Move to the next level
            currentIndex = levelEnd;
            
            // Increase level number
            levelNumber++;
        }
        
        return sortedLevels;
    }
    
    public static void main(String[] args) {
        List<Integer> arr = Arrays.asList(7, 6, 5, 4, 3, 2, 1);
        
        List<List<Integer>> result = levelSort(arr);
        
        // Print all levels
        for (List<Integer> level : result) {
            for (int value : level) {
                System.out.print(value + " ");
            }
            System.out.println();
        }
    }
}
Python
# Python program to get level-wise sorted values of a binary tree

def levelSort(arr):
    # Stores the final sorted levels
    sortedLevels = []
    
    # Points to the first element of the current level
    currentIndex = 0
    
    # Level numbering starts from 1
    levelNumber = 1
    
    # Process levels until all elements are covered
    while currentIndex < len(arr):
        # Calculate the ending position of the current level
        levelEnd = (1 << levelNumber) - 1
        
        # Make sure we do not go outside the array
        levelEnd = min(levelEnd, len(arr))
        
        # Sort only the elements belonging to the current level
        arr[currentIndex:levelEnd] = sorted(arr[currentIndex:levelEnd])
        
        currentLevel = []
        
        # Collect all sorted elements of this level
        for i in range(currentIndex, levelEnd):
            currentLevel.append(arr[i])
        
        # Add the current level to the answer
        sortedLevels.append(currentLevel)
        
        # Move to the next level
        currentIndex = levelEnd
        
        # Increase level number
        levelNumber += 1
    
    return sortedLevels

# Driver code
if __name__ == "__main__":
    arr = [7, 6, 5, 4, 3, 2, 1]
    
    result = levelSort(arr)
    
    # Print all levels
    for level in result:
        print(' '.join(map(str, level)))
C#
// C# program to get level-wise sorted values of a binary tree
using System;
using System.Collections.Generic;
using System.Linq;

class GfG {
    
    static List<List<int>> levelSort(List<int> arr) {
        // Stores the final sorted levels
        List<List<int>> sortedLevels = new List<List<int>>();
        
        // Points to the first element of the current level
        int currentIndex = 0;
        
        // Level numbering starts from 1
        int levelNumber = 1;
        
        // Process levels until all elements are covered
        while (currentIndex < arr.Count) {
            // Calculate the ending position of the current level
            int levelEnd = (1 << levelNumber) - 1;
            
            // Make sure we do not go outside the array
            levelEnd = Math.Min(levelEnd, arr.Count);
            
            // Sort only the elements belonging to the current level
            List<int> subArray = arr.GetRange(currentIndex, levelEnd - currentIndex);
            subArray.Sort();
            for (int i = 0; i < subArray.Count; i++) {
                arr[currentIndex + i] = subArray[i];
            }
            
            List<int> currentLevel = new List<int>();
            
            // Collect all sorted elements of this level
            for (int i = currentIndex; i < levelEnd; i++) {
                currentLevel.Add(arr[i]);
            }
            
            // Add the current level to the answer
            sortedLevels.Add(currentLevel);
            
            // Move to the next level
            currentIndex = levelEnd;
            
            // Increase level number
            levelNumber++;
        }
        
        return sortedLevels;
    }
    
    static void Main(string[] args) {
        List<int> arr = new List<int> { 7, 6, 5, 4, 3, 2, 1 };
        
        List<List<int>> result = levelSort(arr);
        
        // Print all levels
        foreach (List<int> level in result) {
            Console.WriteLine(string.Join(" ", level));
        }
    }
}
JavaScript
// JavaScript program to get level-wise sorted values of a binary tree

function levelSort(arr) {
    // Stores the final sorted levels
    let sortedLevels = [];
    
    // Points to the first element of the current level
    let currentIndex = 0;
    
    // Level numbering starts from 1
    let levelNumber = 1;
    
    // Process levels until all elements are covered
    while (currentIndex < arr.length) {
        // Calculate the ending position of the current level
        let levelEnd = (1 << levelNumber) - 1;
        
        // Make sure we do not go outside the array
        levelEnd = Math.min(levelEnd, arr.length);
        
        // Get the current level elements
        let currentLevelElements = arr.slice(currentIndex, levelEnd);
        
        // Sort the current level elements
        currentLevelElements.sort((a, b) => a - b);
        
        // Update the original array with sorted values
        for (let i = 0; i < currentLevelElements.length; i++) {
            arr[currentIndex + i] = currentLevelElements[i];
        }
        
        let currentLevel = [];
        
        // Collect all sorted elements of this level
        for (let i = currentIndex; i < levelEnd; i++) {
            currentLevel.push(arr[i]);
        }
        
        // Add the current level to the answer
        sortedLevels.push(currentLevel);
        
        // Move to the next level
        currentIndex = levelEnd;
        
        // Increase level number
        levelNumber++;
    }
    
    return sortedLevels;
}

// Driver code
let arr = [7, 6, 5, 4, 3, 2, 1];

let result = levelSort(arr);

// Print all levels
for (let level of result) {
    console.log(level.join(' '));
}

Output
7 
5 6 
1 2 3 4 
Comment