LeetCode/cs/minimum-number-of-operations-to-sort-a-binary-tree-by-level.cs

51 lines
1.2 KiB
C#

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;
}
}