#2471
Minimum Number of Operations to Sort a Binary Tree by Level
MediumTreeBreadth-First SearchBinary TreeCycle DetectionBreadth-First Search
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a level-order traversal to gather values at each level and then counts the minimum number of swaps needed to sort each level using a more efficient approach based on the concept of cycles in permutations.
⚙️
Algorithm
3 steps- 1Step 1: Perform a level-order traversal (BFS) to collect values at each level of the binary tree.
- 2Step 2: For each level, create a sorted version of the level values and map the original indices to their sorted positions.
- 3Step 3: Count the number of swaps needed to sort the level using the cycle detection method.
solution.py42 lines
1from collections import deque
2
3def minOperations(root):
4 if not root:
5 return 0
6 levels = []
7 queue = deque([root])
8 while queue:
9 level_size = len(queue)
10 level = []
11 for _ in range(level_size):
12 node = queue.popleft()
13 level.append(node.val)
14 if node.left:
15 queue.append(node.left)
16 if node.right:
17 queue.append(node.right)
18 levels.append(level)
19
20 def count_swaps(arr):
21 sorted_arr = sorted(arr)
22 index_map = {value: idx for idx, value in enumerate(arr)}
23 visited = [False] * len(arr)
24 swaps = 0
25
26 for i in range(len(arr)):
27 if visited[i] or arr[i] == sorted_arr[i]:
28 continue
29 cycle_size = 0
30 j = i
31 while not visited[j]:
32 visited[j] = True
33 j = index_map[sorted_arr[j]]
34 cycle_size += 1
35 if cycle_size > 0:
36 swaps += (cycle_size - 1)
37 return swaps
38
39 total_swaps = 0
40 for level in levels:
41 total_swaps += count_swaps(level)
42 return total_swapsℹ
Complexity note: The time complexity is O(n) because we traverse each level once and count swaps using cycle detection, which is linear. The space complexity is O(n) due to the storage of level values and the index map.
- 1Each level can be sorted independently.
- 2Swaps can be minimized by using cycle detection in permutations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.