Skip to content

Commit 3bee590

Browse files
authored
Create 2471-minimum-number-of-operations-to-sort-a-binary-tree-by-level.js
1 parent 231b204 commit 3bee590

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @return {number}
12+
*/
13+
var minimumOperations = function(root) {
14+
let res = 0
15+
let q = []
16+
q.push(root)
17+
18+
while(q.length) {
19+
const nxt = []
20+
res += minSwaps(q.map(e => e.val), q.length)
21+
const len = q.length
22+
23+
for(let i = 0; i < len; i++) {
24+
const cur = q[i]
25+
if(cur.left) nxt.push(cur.left)
26+
if(cur.right) nxt.push(cur.right)
27+
}
28+
29+
q = nxt
30+
}
31+
32+
33+
return res
34+
};
35+
36+
function swap(arr, i, j)
37+
{
38+
let temp = arr[i];
39+
arr[i] = arr[j];
40+
arr[j] = temp;
41+
}
42+
43+
// Return the minimum number
44+
// of swaps required to sort
45+
// the array
46+
function minSwaps(arr,N)
47+
{
48+
let ans = 0;
49+
let temp = arr.slice();
50+
51+
// Hashmap which stores the
52+
// indexes of the input array
53+
let h = new Map();
54+
55+
temp.sort((a, b) => a - b);
56+
for (let i = 0; i < N; i++)
57+
{
58+
h.set(arr[i], i);
59+
}
60+
for (let i = 0; i < N; i++)
61+
{
62+
63+
// This is checking whether
64+
// the current element is
65+
// at the right place or not
66+
if (arr[i] != temp[i])
67+
{
68+
ans++;
69+
let init = arr[i];
70+
71+
// If not, swap this element
72+
// with the index of the
73+
// element which should come here
74+
swap(arr, i, h.get(temp[i]));
75+
76+
// Update the indexes in
77+
// the hashmap accordingly
78+
h.set(init,h.get(temp[i]));
79+
h.set(temp[i],i);
80+
}
81+
}
82+
// console.log(arr, ans)
83+
return ans;
84+
}

0 commit comments

Comments
 (0)