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:
parent
b7e7bc1b0f
commit
1888a23f4e
1 changed files with 51 additions and 0 deletions
|
@ -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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue