cs: add «2471. Minimum Number of Operations to Sort a Binary Tree by Level»

URL:	https://leetcode.com/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-12-23 22:19:08 +01:00
parent b7e7bc1b0f
commit 1888a23f4e
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,51 @@
public class Solution {
private int GetSwaps(int[] level) {
int[] sorted = (int[])level.Clone();
Array.Sort(sorted);
var indices = new Dictionary<int, int>();
for (int i = 0; i < level.Length; ++i) {
indices[level[i]] = i;
}
var swaps = 0;
for (int i = 0; i < level.Length; ++i) {
if (level[i] == sorted[i]) {
continue;
}
++swaps;
var current = indices[sorted[i]];
indices[level[i]] = current;
level[current] = level[i];
}
return swaps;
}
public int MinimumOperations(TreeNode root) {
var q = new Queue<TreeNode>();
q.Enqueue(root);
var swaps = 0;
while (q.Count > 0) {
var size = q.Count;
var level = new int[size];
for (int i = 0; i < size; ++i) {
var node = q.Dequeue();
level[i] = node.val;
foreach (var n in new TreeNode[] { node.left, node.right }) {
if (n != null) {
q.Enqueue(n);
}
}
}
swaps += GetSwaps(level);
}
return swaps;
}
}