DFS + value swap
\n\nint ans = 0;\nvector<vector<int>>num;\nvoid dfs(TreeNode *root, int level){\n\tif(root == NULL)return;\n\tif(level >= num.size()){\n\t\tnum.push_back({root-
```\n\nint ans = 0;\nvector<vector<int>>num;\nvoid dfs(TreeNode *root, int level){\n\tif(root == NULL)return;\n\tif(level >= num.size()){\n\t\tnum.push_back({root->val});\n\t}\n\telse{\n\t\tnum[level].push_back(root->val);\n\t}\n\tdfs(root->left, level+1);\n\tdfs(root->right, level+1);\n}\nint minimumOperations(TreeNode* root) {\n\tdfs(root, 0); // stores all the element on same depth in same vector in the order of from leftmost element to rightmost element \n\tfor(vector<int> &vec:num){\n\t\tmap<int, int>map1; // using ordered map as traversing it is same as traversing a sorted vector\n\t\tfor(int index=0;index<vec.size();index++){\n\t\t\tmap1[vec[index]] = index;\n\t\t}\n\t\tint index = 0;\n\t\tfor(auto &pr:map1){\n\t\t\tif(pr.second != index){ // The current element is not where it should be so we swap its place with the element which is currently present on the desired position\n\t\t\t\tans++;\n\t\t\t\tmap1[vec[index]] = pr.second;\n\t\t\t\tswap(vec[index], vec[pr.second]);\n\t\t\t\tpr.second = index;\n\t\t\t}\n\t\t\tindex++;\n\t\t}\n\t}\n\treturn ans;\n}\n```
['Depth-First Search', 'Recursion']