leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

2471.cpp (832B)


      1 class Solution {
      2   public:
      3     int minimumOperations(TreeNode *root) {
      4         queue<TreeNode *> q;
      5         q.push(root);
      6         int res = 0;
      7         while (!q.empty()) {
      8             vector<int> lvl, idx(q.size());
      9             for (int k = q.size(); k > 0; k--) {
     10                 TreeNode *root = q.front();
     11                 q.pop();
     12                 lvl.push_back(root->val);
     13                 if (root->left) q.push(root->left);
     14                 if (root->right) q.push(root->right);
     15             }
     16             iota(begin(idx), end(idx), 0);
     17             sort(begin(idx), end(idx), [&](const int i, const int j) { return lvl[i] < lvl[j]; });
     18             for (int i = 0; i < idx.size(); i++) {
     19                 for (; idx[i] != i; res++)
     20                     swap(idx[i], idx[idx[i]]);
     21             }
     22         }
     23         return res;
     24     }
     25 };