Minimum Number of Operations to Sort a Binary Tree by Level - Problem

You're given a binary tree where each node contains a unique value. Your task is to sort each level of the tree in strictly increasing order using the minimum number of swap operations possible.

The Challenge: In one operation, you can choose any two nodes at the same level and swap their values. You cannot swap values between different levels - only nodes that are at the same distance from the root.

Goal: Return the minimum number of swaps needed to make all levels sorted from left to right in ascending order.

Example: If a level contains values [7, 6, 8, 5], you need to determine the minimum swaps to make it [5, 6, 7, 8].

Input & Output

example_1.py — Basic Tree
$ Input: root = [1,4,3,7,6,8,5]
Output: 3
💡 Note: Level 1: [1] (already sorted). Level 2: [4,3] → swap to get [3,4] (1 swap). Level 3: [7,6,8,5] → need 2 swaps to get [5,6,7,8]. Total: 0 + 1 + 2 = 3 swaps.
example_2.py — Already Sorted
$ Input: root = [1,3,2,7,6,5,4]
Output: 3
💡 Note: Level 1: [1] (sorted). Level 2: [3,2] → 1 swap to get [2,3]. Level 3: [7,6,5,4] → 2 swaps minimum to get [4,5,6,7]. Total: 3 swaps.
example_3.py — Single Node
$ Input: root = [1]
Output: 0
💡 Note: Only one node, already sorted at every level. No swaps needed.

Constraints

  • The number of nodes in the tree is in the range [1, 105]
  • 1 ≤ Node.val ≤ 105
  • All values in the tree are unique
  • The tree is guaranteed to be a valid binary tree

Visualization

Tap to expand
Binary Tree Level Sort - BFS Approach INPUT Binary Tree Structure 1 L0 4 3 L1 7 6 8 5 L2 Input Array: 1 4 3 7 6 8 5 Level 0: [1] - sorted Level 1: [4,3] - unsorted Level 2: [7,6,8,5] - unsorted ALGORITHM STEPS 1 BFS Traversal Process tree level by level 2 Count Min Swaps For each level, find cycles 3 Cycle Detection swaps = cycle_len - 1 4 Sum All Swaps Total across all levels Level 1: [4,3] --> [3,4] 4 3 1 swap Level 2: [7,6,8,5] 7 6 8 5 --> [5,6,7,8] Cycle: 7-->8-->5-->7 = 2 swaps Total: 1 + 2 = 3 swaps FINAL RESULT Sorted Binary Tree 1 3 4 5 6 7 8 All levels sorted: L0: [1] - OK L1: [3,4] - OK L2: [5,6,7,8] - OK Output: 3 Key Insight: The minimum swaps to sort an array equals the sum of (cycle_length - 1) for each cycle. BFS ensures we process each level independently. For Level 2: [7,6,8,5], we have one cycle of length 3 (indices 0-->2-->3-->0), requiring 2 swaps. Level 1 needs 1 swap. Total = 3. TutorialsPoint - Minimum Number of Operations to Sort a Binary Tree by Level | BFS Approach
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
78.7K Views
Medium-High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen