> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Minimum Number of Operations to Sort a Binary

> Tested Python solution for LeetCode 2471 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 2471, [Medium](/catalog/medium). Topics: [Tree](/catalog/topics/tree), [Breadth-First Search](/catalog/topics/breadth-first-search), [Binary Tree](/catalog/topics/binary-tree). [View on LeetCode](https://leetcode.com/problems/minimum-operations-to-sort-a-binary-tree-by-level/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 2471   # by problem number
lcpy gen -s minimum_operations_to_sort_a_binary_tree_by_level   # by problem name
```

## Problem

You are given the `root` of a binary tree with **unique values**.

In one operation, you can choose any two nodes **at the same level** and swap their values.

Return the minimum number of operations needed to make the values at each level sorted in a **strictly increasing order**.

The **level** of a node is the number of edges along the path between it and the root node.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2022/09/18/image-20220918174006-2.png)

```
Input: root = [1,4,3,7,6,8,5,null,null,null,null,9,null,10]
Output: 3
Explanation:
- Swap 4 and 3. The 2nd level becomes [3,4].
- Swap 7 and 5. The 3rd level becomes [5,6,8,7].
- Swap 8 and 7. The 3rd level becomes [5,6,7,8].
We used 3 operations so return 3.
It can be proven that 3 is the minimum number of operations needed.
```

![Example 2](https://assets.leetcode.com/uploads/2022/09/18/image-20220918174026-3.png)

```
Input: root = [1,3,2,7,6,5,4]
Output: 3
Explanation:
- Swap 3 and 2. The 2nd level becomes [2,3].
- Swap 7 and 4. The 3rd level becomes [4,6,5,7].
- Swap 6 and 5. The 3rd level becomes [4,5,6,7].
We used 3 operations so return 3.
It can be proven that 3 is the minimum number of operations needed.
```

![Example 3](https://assets.leetcode.com/uploads/2022/09/18/image-20220918174052-4.png)

```
Input: root = [1,2,3,4,5,6]
Output: 0
Explanation: Each level is already sorted in increasing order so return 0.
```

### Constraints

* The number of nodes in the tree is in the range \[1, 10^5]
* 1 \<= Node.val \<= 10^5
* All the values of the tree are unique

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/minimum_operations_to_sort_a_binary_tree_by_level/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/minimum_operations_to_sort_a_binary_tree_by_level/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import TreeNode


class Solution:
    # Time: O(n log n)
    # Space: O(n)
    def minimum_operations(self, root: TreeNode[int] | None) -> int:
        if root is None:
            return 0

        total = 0
        level = [root]
        while level:
            total += self._min_swaps([node.val for node in level])
            level = [child for node in level for child in (node.left, node.right) if child]
        return total

    def _min_swaps(self, vals: list[int]) -> int:
        order = sorted(range(len(vals)), key=lambda i: vals[i])
        seen = [False] * len(vals)
        swaps = 0
        for i in range(len(vals)):
            if seen[i] or order[i] == i:
                continue
            cycle = 0
            j = i
            while not seen[j]:
                seen[j] = True
                j = order[j]
                cycle += 1
            swaps += cycle - 1
        return swaps
```

## Complexity

| Time | Space |
| - | - |
| O(n log n) | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.