Swift| Simple Approach| 56ms beats 100%
ApproachCreate a BFS array at every level. for this array check for the swaps.
For checking the minimum swaps in bfs array to make an array sorted, we will use
# Approach
Create a BFS array at every level. for this array check for the swaps.
For checking the minimum swaps in bfs array to make an array sorted, we will use cycle detection method.
In cycle detection method, we will use sorted version of the array and iterate over the bfs array to track the visited nodes and count the cycles, resolving each cycle will take c-1 swaps where c = size of the cycle.
TimeComplexity to calculate swaps would be sorting in nlogn and cycle detection in O(n), hence overall it would be O(nlogn)

 
![Screenshot 2024-12-23 at 3.10.19 PM.png](https://assets.leetcode.com/users/images/826f2a1a-009f-4b68-8d4e-671719724fb7_1734946957.1385138.png)

# Code
```swift []
import Collections
class Solution {
    func minimumOperations(_ root: TreeNode?) -> Int {
        func minimumSwapsToSort(_ arr: [Int]) -> Int {
            var arrWithIndices = arr.enumerated().map {($0.offset, $0.element)}.sorted { $0.1 < $1.1 }
            var visited = Array(repeating: false, count: arr.count)
            var swaps = 0
            for i in 0..<arr.count {
                if visited[i] || arrWithIndices[i].0 == i {
                    continue
                }
                var cycleSize = 0
                var current = i
                while !visited[current] {
                    visited[current] = true
                    current = arrWithIndices[current].0
                    cycleSize += 1
                }
                if cycleSize > 1 {
                    swaps += (cycleSize - 1)
                }
            }
            return swaps
        }
        var result = 0
        var bfsQueue = Deque<TreeNode?>()
        bfsQueue.append(root)
        while !bfsQueue.isEmpty {
            var intermediateQueue = Deque<TreeNode?>()
            var currArray = Array<Int>()
            while !bfsQueue.isEmpty {
                let first = bfsQueue.popFirst()!
                if let leftChild = first?.left {
                    intermediateQueue.append(leftChild)
                }
                if let rightChild = first?.right {
                    intermediateQueue.append(rightChild)
                }
                currArray.append(first?.val ?? 0)
            }
            bfsQueue = intermediateQueue
            result += minimumSwapsToSort(currArray)
        }
        return result
    }
}
```
['Swift']