JAVA | Level Order Traversal + Cyclic Sort
Please Upvote :D\n\nclass Solution {\n    public int minimumOperations(TreeNode root) {\n        Queue<TreeNode> q = new LinkedList<>();\n        q.add(root);\n
### **Please Upvote** :D\n```\nclass Solution {\n    public int minimumOperations(TreeNode root) {\n        Queue<TreeNode> q = new LinkedList<>();\n        q.add(root);\n\n        int min = 0;\n\n        while (!q.isEmpty()){\n            int size = q.size();\n            int[] arr = new int[size];\n            int i = 0;\n\n            while (size-- > 0){\n                TreeNode node = q.poll();\n                arr[i++] = node.val;\n\n                if (node.left != null) q.add(node.left);\n                if (node.right != null) q.add(node.right);\n            }\n\n            min += minSwaps(arr);\n        }\n\n        return min;\n    }\n\n    public int minSwaps(int[] nums) {\n        Map<Integer, Integer> map = new HashMap<>();\n        int n = nums.length;\n\n        for (int i = 0; i < n; i++) {\n            map.put(nums[i], i);\n        }\n\n        Arrays.sort(nums);\n        boolean[] visited = new boolean[n];\n\n        int ans = 0;\n\n        for (int i = 0; i < n; i++) {\n            if (visited[i] || map.get(nums[i]) == i) {\n                continue;\n            }\n\n            int j = i, cycleSize = 0;\n\n            while (!visited[j]) {\n                visited[j] = true;\n                j = map.get(nums[j]);\n                cycleSize++;\n            }\n\n            if(cycleSize > 0) {\n                ans += (cycleSize - 1);\n            }\n        }\n\n        return ans;\n    }\n}\n\n// TC: O(h * n * logn)\n// SC: O(n)\n```
['Breadth-First Search', 'Sorting', 'Java']