Graph-based Approach Cycle count 
Intuition 💡The task is to make the values at each level of a binary tree sorted in strictly increasing order by performing the minimum number of operations, whe
# Intuition 💡  
The task is to make the values at each level of a binary tree sorted in strictly increasing order by performing the minimum number of operations, where in each operation, we can swap any two nodes that are at the same level.

At a high level, we can solve this by:
1. **Performing a level-order traversal** to gather the node values at each level.
2. **Sorting** these values at each level while tracking their original indices.
3. **Detecting the minimum number of swaps** needed to rearrange the node values in sorted order.

The key observation here is that sorting the values can be reduced to counting the number of **cycles** in the permutation of values, and the minimum number of swaps needed to fix each cycle is `cycle size - 1`.

---

# Approach 🚀  

### 1. **Level-Order Traversal 🌲**  
   - We traverse the binary tree level by level using **BFS (Breadth-First Search)**.
   - At each level, we gather all the node values into a list for sorting.
   - This ensures that all nodes at a given depth are processed together.
   - The BFS ensures that we explore each node once, allowing us to collect node values at each level efficiently.

### 2. **Sorting the Values at Each Level 🔄**  
   - Once we have all the values of nodes at a level, we need to sort them.
   - To minimize the swaps, we must track the positions of the values after sorting, so we can figure out where each element originally belonged.
   - We can achieve this by storing each node’s value along with its original index and then sorting this list by the node values.
   - After sorting, the original indices tell us where the values should move to.

### 3. **Cycle Detection to Find Minimum Swaps 🔍**  
   - To compute the minimum number of swaps, we must identify **cycles** in the index mapping:
     - If a node is already in the correct position or has already been visited, we skip it.
     - If a node is out of place, it belongs to a cycle where it needs to be swapped into its correct position.
     - For a cycle of size `k`, the minimum number of swaps required is `k - 1`.
   - We can track visited nodes using a `visited` array and process each cycle individually.

### 4. **Total Swaps for All Levels ➕**  
   - Once we calculate the number of swaps for each level, we sum them up to get the total minimum operations required for the entire tree.

---

# Complexity 📊  

- **Time Complexity**:  
  - **Tree Traversal**: `O(n)`, where `n` is the total number of nodes in the tree. Every node is processed once during the BFS.
  - **Sorting Each Level**: Sorting at each level requires `O(k log k)` time, where `k` is the number of nodes at that level.
  - Overall, the time complexity is dominated by the sorting operations. Since the total number of nodes across all levels is `n`, the overall time complexity is **`O(n log n)`**.

- **Space Complexity**:  
  - We store the values and their indices for each level, so the space complexity for storing node values at a level is `O(k)`, where `k` is the number of nodes at that level.
  - The BFS queue also uses `O(n)` space, as it holds nodes at all levels.
  - Hence, the total space complexity is **`O(n)`**.

---

# Code 🧑‍💻

```cpp []
class Solution {
public:
    int minSwapsToSort(vector<int>& arr) {
        int n = arr.size();
        vector<pair<int, int>> indexedArr;
        for (int i = 0; i < n; ++i) {
            indexedArr.push_back({arr[i], i});
        }
        sort(indexedArr.begin(), indexedArr.end());
        vector<bool> visited(n, false);
        int swaps = 0;

        for (int i = 0; i < n; ++i) {
            if (visited[i] || indexedArr[i].second == i) {
                continue;
            }

            int cycleSize = 0;
            int j = i;
            while (!visited[j]) {
                visited[j] = true;
                j = indexedArr[j].second;
                ++cycleSize;
            }

            if (cycleSize > 1) {
                swaps += cycleSize - 1;
            }
        }

        return swaps;
    }

    int minimumOperations(TreeNode* root) {
        if (!root) return 0;

        queue<TreeNode*> q;
        q.push(root);
        int operations = 0;

        while (!q.empty()) {
            int levelSize = q.size();
            vector<int> level;

            for (int i = 0; i < levelSize; ++i) {
                TreeNode* node = q.front();
                q.pop();
                level.push_back(node->val);

                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
            }

            operations += minSwapsToSort(level);
        }

        return operations;
    }
};
```
```Java []
class Solution {
    public int minSwapsToSort(int[] arr) {
        int n = arr.length;
        int[][] indexedArr = new int[n][2];
        for (int i = 0; i < n; i++) {
            indexedArr[i][0] = arr[i];
            indexedArr[i][1] = i;
        }
        Arrays.sort(indexedArr, (a, b) -> Integer.compare(a[0], b[0]));
        boolean[] visited = new boolean[n];
        int swaps = 0;

        for (int i = 0; i < n; i++) {
            if (visited[i] || indexedArr[i][1] == i) {
                continue;
            }

            int cycleSize = 0;
            int j = i;
            while (!visited[j]) {
                visited[j] = true;
                j = indexedArr[j][1];
                cycleSize++;
            }

            if (cycleSize > 1) {
                swaps += cycleSize - 1;
            }
        }

        return swaps;
    }

    public int minimumOperations(TreeNode root) {
        if (root == null) return 0;

        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        int operations = 0;

        while (!q.isEmpty()) {
            int levelSize = q.size();
            int[] level = new int[levelSize];
            for (int i = 0; i < levelSize; i++) {
                TreeNode node = q.poll();
                level[i] = node.val;

                if (node.left != null) q.add(node.left);
                if (node.right != null) q.add(node.right);
            }
            operations += minSwapsToSort(level);
        }

        return operations;
    }
}
```
```Python3 []
class Solution:
    def minSwapsToSort(self, arr):
        n = len(arr)
        indexedArr = [(arr[i], i) for i in range(n)]
        indexedArr.sort()
        visited = [False] * n
        swaps = 0

        for i in range(n):
            if visited[i] or indexedArr[i][1] == i:
                continue

            cycleSize = 0
            j = i
            while not visited[j]:
                visited[j] = True
                j = indexedArr[j][1]
                cycleSize += 1

            if cycleSize > 1:
                swaps += cycleSize - 1

        return swaps

    def minimumOperations(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0

        queue = [root]
        operations = 0

        while queue:
            levelSize = len(queue)
            level = []

            for _ in range(levelSize):
                node = queue.pop(0)
                level.append(node.val)

                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)

            operations += self.minSwapsToSort(level)

        return operations
```
```JavaScript []
var minSwapsToSort = function(arr) {
    const n = arr.length;
    const indexedArr = arr.map((val, index) => [val, index]);
    indexedArr.sort((a, b) => a[0] - b[0]);
    const visited = Array(n).fill(false);
    let swaps = 0;

    for (let i = 0; i < n; i++) {
        if (visited[i] || indexedArr[i][1] === i) {
            continue;
        }

        let cycleSize = 0;
        let j = i;
        while (!visited[j]) {
            visited[j] = true;
            j = indexedArr[j][1];
            cycleSize++;
        }

        if (cycleSize > 1) {
            swaps += cycleSize - 1;
        }
    }

    return swaps;
};

var minimumOperations = function(root) {
    if (!root) return 0;

    let queue = [root];
    let operations = 0;

    while (queue.length) {
        const levelSize = queue.length;
        const level = [];

        for (let i = 0; i < levelSize; i++) {
            const node = queue.shift();
            level.push(node.val);

            if (node.left) queue.push(node.left);
            if (node.right) queue.push(node.right);
        }

        operations += minSwapsToSort(level);
    }

    return operations;
};
```
```C []
int minSwapsToSort(int* arr, int n) {
    int indexedArr[n][2];
    for (int i = 0; i < n; i++) {
        indexedArr[i][0] = arr[i];
        indexedArr[i][1] = i;
    }
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (indexedArr[j][0] > indexedArr[j + 1][0]) {
                int temp = indexedArr[j][0];
                indexedArr[j][0] = indexedArr[j + 1][0];
                indexedArr[j + 1][0] = temp;

                temp = indexedArr[j][1];
                indexedArr[j][1] = indexedArr[j + 1][1];
                indexedArr[j + 1][1] = temp;
            }
        }
    }
    int visited[n];
    for (int i = 0; i < n; i++) {
        visited[i] = 0;
    }
    int swaps = 0;

    for (int i = 0; i < n; i++) {
        if (visited[i] || indexedArr[i][1] == i) {
            continue;
        }

        int cycleSize = 0;
        int j = i;
        while (!visited[j]) {
            visited[j] = 1;
            j = indexedArr[j][1];
            cycleSize++;
        }

        if (cycleSize > 1) {
            swaps += cycleSize - 1;
        }
    }

    return swaps;
}

int minimumOperations(struct TreeNode* root) {
    if (root == NULL) return 0;

    struct TreeNode* queue[1000];
    int front = 0, rear = 0;
    queue[rear++] = root;
    int operations = 0;

    while (front < rear) {
        int levelSize = rear - front;
        int level[levelSize];

        for (int i = 0; i < levelSize; i++) {
            struct TreeNode* node = queue[front++];
            level[i] = node->val;

            if (node->left) queue[rear++] = node->left;
            if (node->right) queue[rear++] = node->right;
        }

        operations += minSwapsToSort(level, levelSize);
    }

    return operations;
}
```
```C# []
public class Solution {
    public int MinSwapsToSort(int[] arr) {
        int n = arr.Length;
        var indexedArr = new Tuple<int, int>[n];
        for (int i = 0; i < n; i++) {
            indexedArr[i] = Tuple.Create(arr[i], i);
        }
        Array.Sort(indexedArr, (a, b) => a.Item1.CompareTo(b.Item1));
        bool[] visited = new bool[n];
        int swaps = 0;

        for (int i = 0; i < n; i++) {
            if (visited[i] || indexedArr[i].Item2 == i) {
                continue;
            }

            int cycleSize = 0;
            int j = i;
            while (!visited[j]) {
                visited[j] = true;
                j = indexedArr[j].Item2;
                cycleSize++;
            }

            if (cycleSize > 1) {
                swaps += cycleSize - 1;
            }
        }

        return swaps;
    }

    public int MinimumOperations(TreeNode root) {
        if (root == null) return 0;

        var queue = new Queue<TreeNode>();
        queue.Enqueue(root);
        int operations = 0;

        while (queue.Count > 0) {
            int levelSize = queue.Count;
            var level = new int[levelSize];
            for (int i = 0; i < levelSize; i++) {
                TreeNode node = queue.Dequeue();
                level[i] = node.val;

                if (node.left != null) queue.Enqueue(node.left);
                if (node.right != null) queue.Enqueue(node.right);
            }

            operations += MinSwapsToSort(level);
        }

        return operations;
    }
}
```

['C', 'C++', 'Java', 'Python3', 'JavaScript', 'C#']