Java Level Order Traversal solution with Cycle Detection & DFS | Time Complexity: O(NlogN)
IntuitionTo solve the problem, we need to sort the values at each level of a binary tree with the minimum number of swaps. The key insights are:

Level Traversa
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
To solve the problem, we need to sort the values at each level of a binary tree with the minimum number of swaps. The key insights are:

1. **Level Traversal**:
    - A binary tree can be traversed level by level using either BFS (queue) or recursive DFS. At each level, we extract the node values into an array.

2. **Sorting with Minimum Swaps**:
    - To minimize swaps for sorting, we identify cycles in the array of indices after sorting. Each cycle contributes (cycle size - 1) swaps.
# Approach
<!-- Describe your approach to solving the problem. -->
1. **Binary Tree Traversal (Level Collection)**:
    - Use a Depth-First Search (DFS) approach to traverse the binary tree and collect values level by level.
    - For each level, store the node values in a list. These lists represent the unsorted node values for each level of the tree.

2. **Sorting with Minimum Swaps**:
    - For each level, the goal is to sort the node values in strictly increasing order with the minimum number of swaps.
    - This can be achieved by leveraging cycle detection in a permutation:
        - First, pair each value with its index in the original list.
        - Sort the list based on values while preserving the original indices.
        - Treat the sorted indices as a graph, where each index points to its target position.
        - Traverse this "graph" to detect cycles.
        - The number of swaps needed for a cycle of length n is n−1.

3. **Repeat for All Levels**:
    - Perform the sorting and cycle detection process for every level in the binary tree.
    - Accumulate the total number of swaps required for all levels.
4. **Final Output**:
    - Return the total swap count as the minimum number of operations needed to make all levels sorted in strictly increasing order.

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

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

# Code
```java []
class Solution {
    public int minimumOperations(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int swapCount = 0; // To track the total swaps
        int level = 0; // To track the current level
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        // Level-order traversal of the tree
        while (!queue.isEmpty()) {
            int levelSize = queue.size(); // Number of nodes at the current level
            int[] tempArray = new int[levelSize]; //Temp array for current level values

            // Extract values of current level
            for (int i = 0; i < levelSize; i++) {
                TreeNode currentNode = queue.poll();
                tempArray[i] = currentNode.val; //Add the node value to tempArray
                if (currentNode.left != null) queue.offer(currentNode.left);
                if (currentNode.right != null) queue.offer(currentNode.right);
            }

            // Pass tempArray to swapping method
            swapCount += calculateSwaps(tempArray);
            level++; //Increment level
        }

        return swapCount; //Return the total swap count
    }

    // Helper method to calculate minimum swaps needed 
    private int calculateSwaps(int[] tempArray) {
        int n = tempArray.length;
        int swapCount = 0;

        //pair values with their indices
        int[][] paired = new int[n][2];
        for (int i = 0; i < n; i++) {
            paired[i][0] = tempArray[i]; //Value
            paired[i][1] = i; //Original index
        }

        //Sort the array based on values
        Arrays.sort(paired, (a, b) -> Integer.compare(a[0], b[0]));

        //Visited array to track if an element has been placed correctly
        boolean[] visited = new boolean[n];

        for (int i = 0; i < n; i++) {
            // Skip if already visited or in the correct position
            if (visited[i] || paired[i][1] == i) {
                continue;
            }

            // Calculate the size of the cycle
            int cycleSize = 0;
            int j = i;

            while (!visited[j]) {
                visited[j] = true;
                j = paired[j][1]; //Move to the next index in the cycle
                cycleSize++;
            }

            // If the cycle has size > 1, we need (cycleSize - 1) swaps
            if (cycleSize > 1) {
                swapCount += cycleSize - 1;
            }
        }

        return swapCount;
    }
}

```
['Array', 'Math', 'Tree', 'Depth-First Search', 'Java']