Skip to content

Commit cbd0d13

Browse files
authored
Create 2471. Minimum Number of Operations to Sort a Binary Tree by Level (#669)
2 parents 2621610 + 55e5e2a commit cbd0d13

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
int minimumOperations(TreeNode* root) {
15+
int ans = 0;
16+
queue<TreeNode*> q{{root}};
17+
while (!q.empty()){
18+
vector<int> vals;
19+
vector<int> child(q.size());
20+
for (int size = q.size(); size > 0; size--){
21+
TreeNode* node = q.front();
22+
q.pop();
23+
vals.push_back(node->val);
24+
if (node->left != nullptr)
25+
q.push(node->left);
26+
if (node->right != nullptr)
27+
q.push(node->right);
28+
}
29+
iota(child.begin(), child.end(), 0);
30+
ranges::sort(child, [&vals](int i, int j){ return vals[i] < vals[j]; });
31+
for (int i = 0; i < child.size(); i++)
32+
for ( ;child[i] != i; ans++)
33+
swap(child[i], child[child[i]]);
34+
}
35+
return ans;
36+
}
37+
};

0 commit comments

Comments
 (0)