Intuitive Solution | Easiest method | Clean Code with explanation
IntuitionWe need to solve each level separately.ApproachWe build upon the previously known solution to find minimum number of swaps to sort an array.We just do
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
We need to solve each level separately.

# Approach
<!-- Describe your approach to solving the problem. -->
We build upon the previously known solution to find minimum number of swaps to sort an array.

We just do it for each level separately. Level Order Traversal seems a right way to do it.

# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n * lg(n))

- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```java []
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int minimumOperations(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        int ops = 0;

        while (!q.isEmpty())
        {
            int sz = q.size();

            // A 2-D array to store the node values and their original index(order)
            int[][] levelNodes = new int[sz][2];

            // Level Order Traversal
            for (int i = 0; i < sz; i++)
            {
                TreeNode node = q.poll();

                if (node.left != null)
                    q.add(node.left);
                if (node.right != null)
                    q.add(node.right);
                
                levelNodes[i][0] = node.val;
                levelNodes[i][1] = i;
            }

            // Sorting the 2-D array based on the node values
            Arrays.sort(levelNodes, Comparator.comparingInt(a -> a[0]));

            for (int i = 0; i < sz; i++)
            {
                // send the node to the correct position by swapping
                while (levelNodes[i][1] != i)
                {
                    swap(levelNodes, i, levelNodes[i][1]);
                    ops++;
                }
            }
        }

        return ops;
    }

    // Method to swap the indexes. Only swapping the indexes would suffice, since we only need the count of swaps.
    private void swap(int[][] levelNodes, int i, int j)
    {
        int temp = levelNodes[i][1];
        levelNodes[i][1] = levelNodes[j][1];
        levelNodes[j][1] = temp;
    }
}
```
['Java']