BFS easy to understand
\nclass Solution {\n    public int minimumOperations(TreeNode root) {\n        int ans = 0;\n        Queue<TreeNode> q = new LinkedList<>();\n        q.add(root
```\nclass Solution {\n    public int minimumOperations(TreeNode root) {\n        int ans = 0;\n        Queue<TreeNode> q = new LinkedList<>();\n        q.add(root);\n        while(!q.isEmpty()){\n            int size = q.size();\n            List<Integer> list = new ArrayList<>();\n            while(size-->0){\n                TreeNode node = q.poll();\n                list.add(node.val);\n                if(node.left!=null){\n                    q.add(node.left);\n                }\n                if(node.right!=null){\n                    q.add(node.right);\n                }\n            }\n            ans+=minSwaps(list);\n            \n        }\n        return ans;\n    }\n      public int minSwaps(List<Integer> list) {\n        int n = list.size();\n\n        // Create a list of pairs (value, index)\n        List<Pair> pairs = new ArrayList<>();\n        for (int i = 0; i < n; i++) {\n            pairs.add(new Pair(list.get(i), i));\n        }\n\n        // Sort the list of pairs based on the values\n        pairs.sort(Comparator.comparingInt(p -> p.value));\n\n        // Create a visited array to keep track of visited indices\n        boolean[] visited = new boolean[n];\n        Arrays.fill(visited, false);\n\n        int swaps = 0;\n\n        // Iterate through the list to detect cycles\n        for (int i = 0; i < n; i++) {\n            // If already visited or already in the correct position\n            if (visited[i] || pairs.get(i).index == i) {\n                continue;\n            }\n\n            // Calculate the size of the cycle\n            int cycleSize = 0;\n            int j = i;\n            while (!visited[j]) {\n                visited[j] = true;\n                j = pairs.get(j).index; // Move to the next index in the cycle\n                cycleSize++;\n            }\n\n            // Add (cycleSize - 1) to swaps for this cycle\n            if (cycleSize > 1) {\n                swaps += (cycleSize - 1);\n            }\n        }\n\n        return swaps;\n    }\n\n}\nclass Pair {\n        int value, index;\n\n        Pair(int value, int index) {\n            this.value = value;\n            this.index = index;\n        }\n    }\n```
['Tree', 'Breadth-First Search', 'Sorting', 'Java']