2471. Minimum Number of Operations to Sort a Binary Tree by Level
You are given the root of a binary tree with unique values.
In one operation, you can choose any two nodes at the same level and swap their values.
Return the minimum number of operations needed to make the values at each level sorted in a strictly increasing order.
The level of a node is the number of edges along the path between it and the root node.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
class Solution { void dfs(TreeNode* node, vector<vector<int>>& nodes, int dep) { if(!node) return; if(nodes.size() == dep) nodes.emplace_back(); nodes[dep].push_back(node->val); dfs(node->left,nodes,dep + 1); dfs(node->right,nodes,dep + 1); } public: int minimumOperations(TreeNode* root) { vector<vector<int>> nodes; dfs(root, nodes, 0); int res = 0; for(auto& n : nodes) { auto s = n; sort(begin(s), end(s)); unordered_map<int, int> mp; for(int i = 0; i < n.size(); i++) mp[n[i]] = i; for(int i = 0; i < n.size(); i++) { if(n[i] == s[i]) continue; int p = mp[s[i]]; swap(n[p],n[i]); mp[n[i]] = i; mp[n[p]] = p; res += 1; } } return res; } };
|