diff --git a/cs/minimum-number-of-operations-to-sort-a-binary-tree-by-level.cs b/cs/minimum-number-of-operations-to-sort-a-binary-tree-by-level.cs new file mode 100644 index 0000000..fab574a --- /dev/null +++ b/cs/minimum-number-of-operations-to-sort-a-binary-tree-by-level.cs @@ -0,0 +1,51 @@ +public class Solution { + private int GetSwaps(int[] level) { + int[] sorted = (int[])level.Clone(); + Array.Sort(sorted); + + var indices = new Dictionary(); + 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(); + 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; + } +}