Kotlin | Beats 100%
ApproachKeep nodes of current level in list a (initially contains root). At each iteration, build a new list b from children of nodes in a and assing the new li
# Approach
Keep nodes of current level in list `a` (initially contains `root`). At each iteration, build a new list `b` from children of nodes in `a` and assing the new list to `a`.

For nodes in each level, sort the list with original indexes, then look for sorting cycles, each cycle of size `n` takes `n - 1` operations to sort.

# Complexity
- Time complexity: $$O(n•log(n))$$

- Space complexity: $$O(n)$$

# Code
```kotlin []
class Solution {
    fun minimumOperations(root: TreeNode?): Int {
        var a = listOf(root!!)
        var ans = 0
        while (a.isNotEmpty()) {
            ans += countSortMoves(a.map { it.`val` })
            val b = mutableListOf<TreeNode>()
            for (u in a) {
                if (u.left != null) b.add(u.left!!)
                if (u.right != null) b.add(u.right!!)
            }
            a = b
        }
        return ans
    }

    private fun countSortMoves(list: List<Int>): Int {
        val sorted = list.withIndex().sortedBy { it.value }.map { it.index }
        var cnt = 0
        val counted = BooleanArray(list.size)
        for ((i, j) in sorted.withIndex()) {
            if (counted[j] || i == j) continue
            var k = j
            while (k != i) {
                counted[k] = true
                cnt++
                k = sorted[k]
            }
            counted[i] = true
        }
        return cnt
    }
}
```
['Kotlin']