(MAP)-2471. Minimum Number of Operations to Sort a Binary Tree by Level-JAVA(
/*\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode() {}\n * 
/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode() {}\n *     TreeNode(int val) { this.val = val; }\n *     TreeNode(int val, TreeNode left, TreeNode right) {\n *         this.val = val;\n *         this.left = left;\n *         this.right = right;\n *     }\n * }\n */\nclass Solution {\n    public int minimumOperations(TreeNode root) {\n        Queue<TreeNode> q=new LinkedList<>();\n        q.offer(root);\n        int s=0;\n        while(!q.isEmpty())\n        {\n            int m=0,l=q.size();\n            List<Integer> l1=new ArrayList<>();\n            for(int i=0;i<l;i++)\n            {\n                if(q.peek().left!=null)\n                {\n                    q.add(q.peek().left);\n                }\n                if(q.peek().right!=null)\n                {\n                    q.add(q.peek().right);\n                }\n                int f=q.poll().val;\n                l1.add(f);\n            }\n            s+=task(l1);\n        }\n        return s;\n    }\n    public int task(List<Integer> nm)\n    {\n        Map<Integer,Integer> mp=new HashMap<>();\n        for(int i=0;i<nm.size();i++)\n        {\n            mp.put(nm.get(i),i);\n        }\n        Collections.sort(nm);\n        boolean k[]=new boolean[nm.size()];\n        int s=0;\n        for(int i=0;i<nm.size();i++)\n        {\n            if(k[i] || mp.get(nm.get(i))==i)\n            {\n                continue;\n            }\n            int j=i,m=0;\n            while(!k[j])\n            {\n                k[j]=true;\n                j=mp.get(nm.get(j));\n                m++;\n            }\n            if(m>0)\n            {\n                s+=m-1;\n            }\n        }\n        return s;    }\n}
['Java']