Min Swaps Function
Intuition\nBy traversing level wise and adding them to a vector and then we can compute minimum swaps needed.\n Describe your first thoughts on how to solve thi
# Intuition\nBy traversing level wise and adding them to a vector and then we can compute minimum swaps needed.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUsing Breath-First Search to traverse the each level\nAnd function `minSwaps` to compute minmum number of swaps needed to sort.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: *`O(nlogn)`*\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: *`O(n)`*\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    \n    int minSwaps(vector<int>& B, int n) {\n        vector<pair<int, int>>v(n);\n        for(int i = 0; i < n; i++)\n        v[i] = {B[i], i};\t// v = {{4, 0}, {3, 1}, {8, 2}}\n        sort(v.begin(), v.end()); // v = {{3, 1}, {4, 0}, {8, 2}}\n\n        int count = 0;\n        for(int i = 0; i < n ; i++){\n          if(v[i].second == i) continue;\n          else{\n            count ++;\n            swap(v[i], v[v[i].second]);\n            i--;\n          }\n        }\n        \n        return count;\n    }\n    \n    int minimumOperations(TreeNode* root) {\n        int size, swaps = 0;\n        \n        queue<TreeNode*> q;\n        q.push(root);\n        \n        vector<int> level;\n        int i, notM;\n        \n        while(!q.empty()) {\n            size = q.size();\n            while(size--) {\n                root = q.front();\n                q.pop();\n                level.push_back(root->val);\n                if(root->left)\n                    q.push(root->left);\n                if(root->right)\n                    q.push(root->right);\n            }\n            \n            swaps += minSwaps(level, level.size());\n            \n            level.clear();\n        }\n        \n        return swaps;\n    }\n};\n```
['Tree', 'Breadth-First Search', 'C++']