From 1888a23f4e6c29eb6971e4847715dc0dd48227da Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 23 Dec 2024 22:19:08 +0100 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=C2=AB2471.=20Minimum=20Number=20of?= =?UTF-8?q?=20Operations=20to=20Sort=20a=20Binary=20Tree=20by=20Level?= =?UTF-8?q?=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level/ Signed-off-by: Matej Focko --- ...erations-to-sort-a-binary-tree-by-level.cs | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 cs/minimum-number-of-operations-to-sort-a-binary-tree-by-level.cs 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; + } +}