2471. Minimum Number of Operations to Sort a Binary Tree by Level

```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) {

        TreeNode temp = root;
        Queue<TreeNode> helper = new LinkedList<>();
        helper.offer(root);
        int c = 0 ;
        boolean isFirstNode = true ;
        while(!helper.isEmpty()){
            int size = helper.size();
            ArrayList<Integer> values = new ArrayList<>();
            while(size > 0 ){
               TreeNode node = helper.poll();
               if(node.left != null){
                helper.offer(node.left);
                values.add(node.left.val);
               }
               if(node.right != null){
                helper.offer(node.right);
                values.add(node.right.val);
               }
               size--;
            }
            c += findOperations(values);
        }
         return c;

    }

    private static int findOperations(ArrayList<Integer> values){
        
        Map<Integer,Integer> map = new TreeMap<>();
        boolean[] visited = new boolean[values.size()];
        int len = values.size();
        for(int i = 0 ; i < len ; i++){
            map.put(values.get(i), i );
        }
        Collections.sort(values);

        int it = 0 ; 
        int cycle = 0 ;
        System.out.println(map.toString());
        for(Map.Entry<Integer, Integer> m : map.entrySet()){
             int key = m.getKey();
             int index = m.getValue();

             if(index == it){ 
                it++;
                continue;
             }

             if(!visited[index]){
                  while(!visited[index]){

                     key = values.get(index);  
                     visited[index] = true;
                     index = map.get(key);
                     cycle++;
                  }
                  cycle--;
             }
             it++;
        }

       
       if(cycle == 0 )return 0;
        return cycle;
    }
}
```
['Java']