[LeetCode] Minimum Number of Operations to Sort a Binary Tree by Level

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
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;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/13/PS/LeetCode/minimum-number-of-operations-to-sort-a-binary-tree-by-level/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.