Java, Python and C++ Solution
IntuitionThe problem can be solved by level-order traversal of the binary tree, where at each level, we compute the minimum number of swaps required to sort the
# Intuition
The problem can be solved by level-order traversal of the binary tree, where at each level, we compute the minimum number of swaps required to sort the node values. Sorting can be achieved by determining the positions of elements in the sorted array and using a cycle-based swap count approach.

# Approach
1. Perform a level-order traversal (BFS) of the binary tree.
2. For each level:
   - Collect node values into a list (`nums`).
   - Create a sorted version of the list (`sorted_nums`) and map their indices using a dictionary (`sorted_idx`).
   - Calculate the minimum number of swaps required to sort `nums` using a cycle-detection method.
3. Add the number of swaps for each level to a result variable (`res`).
4. Return the total number of swaps.

# Complexity
- Time complexity:  
  $$O(n \log n)$$ for sorting at each level, where **n** is the maximum number of nodes at any level. For **k** levels, the total complexity is approximately **(O(k * nlog n))**.  
  Counting swaps at each level is **O(n)**, resulting in a combined complexity of **O(k * nlog n)**.

- Space complexity:  
  $$O(n)$$ for storing the node values and indices at each level in the deque and dictionary.


```Java []
import java.util.*;

class Solution {
    public int minimumOperations(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        int res = 0;

        while (!q.isEmpty()) {
            List<Integer> nums = new ArrayList<>();
            List<Integer> sortedNums = new ArrayList<>();
            Map<Integer, Integer> sortedIdx = new HashMap<>();

            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = q.poll();
                if (node.left != null) {
                    q.add(node.left);
                    nums.add(node.left.val);
                    sortedNums.add(node.left.val);
                }
                if (node.right != null) {
                    q.add(node.right);
                    nums.add(node.right.val);
                    sortedNums.add(node.right.val);
                }
            }

            Collections.sort(sortedNums);
            for (int i = 0; i < sortedNums.size(); i++) {
                sortedIdx.put(nums.get(i), i);
            }

            for (int i = 0; i < nums.size(); i++) {
                while (!nums.get(i).equals(sortedNums.get(i))) {
                    res++;
                    int temp = nums.get(i);
                    nums.set(i, nums.get(sortedIdx.get(sortedNums.get(i))));
                    nums.set(sortedIdx.get(sortedNums.get(i)), temp);

                    int idx = sortedIdx.get(sortedNums.get(i));
                    sortedIdx.put(nums.get(i), i);
                    sortedIdx.put(temp, idx);
                }
            }
        }
        return res;
    }
}

```
```python []
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def minimumOperations(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: int
        """
        q = deque([root])
        res = 0
        while q:
            sorted_idx = {}
            sorted_nums = []
            nums = []
            for _ in range(len(q)):
                node = q.popleft()
                if node.left:
                    q.append(node.left)
                    nums.append(node.left.val)
                    sorted_nums.append(node.left.val)
                if node.right:
                    q.append(node.right)
                    nums.append(node.right.val)
                    sorted_nums.append(node.right.val)
                
            sorted_nums.sort()
            for index in range(len(sorted_nums)):
                sorted_idx[nums[index]] = index 

            for index in range(len(nums)):
                if nums[index] != sorted_nums[index]:
                    res += 1
                    temp = nums[index]
                    nums[index], nums[sorted_idx[sorted_nums[index]]] = nums[sorted_idx[sorted_nums[index]]], nums[index]
                    idx = sorted_idx[sorted_nums[index]]
                    sorted_idx[nums[index]] = index
                    sorted_idx[temp] = idx
        return res
```
```C++ []
#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    int minimumOperations(TreeNode* root) {
        queue<TreeNode*> q;
        q.push(root);
        int res = 0;

        while (!q.empty()) {
            vector<int> nums, sortedNums;
            unordered_map<int, int> sortedIdx;

            int size = q.size();
            for (int i = 0; i < size; ++i) {
                TreeNode* node = q.front();
                q.pop();
                if (node->left) {
                    q.push(node->left);
                    nums.push_back(node->left->val);
                    sortedNums.push_back(node->left->val);
                }
                if (node->right) {
                    q.push(node->right);
                    nums.push_back(node->right->val);
                    sortedNums.push_back(node->right->val);
                }
            }

            sort(sortedNums.begin(), sortedNums.end());
            for (int i = 0; i < sortedNums.size(); ++i) {
                sortedIdx[nums[i]] = i;
            }

            for (int i = 0; i < nums.size(); ++i) {
                while (nums[i] != sortedNums[i]) {
                    res++;
                    int temp = nums[i];
                    nums[i] = nums[sortedIdx[sortedNums[i]]];
                    nums[sortedIdx[sortedNums[i]]] = temp;

                    int idx = sortedIdx[sortedNums[i]];
                    sortedIdx[nums[i]] = i;
                    sortedIdx[temp] = idx;
                }
            }
        }
        return res;
    }
};

```

['Python', 'C++', 'Java', 'Python3']