leetcode

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

1110.cpp (1050B)


      1 class Solution {
      2   public:
      3     vector<TreeNode *> delNodes(TreeNode *root, const vector<int> &to_delete) {
      4         const unordered_set<int> us(begin(to_delete), end(to_delete));
      5         vector<TreeNode *> res;
      6 
      7         queue<TreeNode *> q;
      8         q.push(root);
      9         while (!q.empty()) {
     10             TreeNode *crnt = q.front();
     11             q.pop();
     12 
     13             bool root = crnt->val > 0;
     14             crnt->val = abs(crnt->val);
     15             bool deleted = us.count(crnt->val);
     16             if (root && !deleted) res.push_back(crnt);
     17 
     18             if (crnt->left) {
     19                 int val = crnt->left->val;
     20                 if (!deleted) crnt->left->val = -val;
     21                 q.push(crnt->left);
     22                 if (us.count(val)) crnt->left = nullptr;
     23             }
     24 
     25             if (crnt->right) {
     26                 int val = crnt->right->val;
     27                 if (!deleted) crnt->right->val = -val;
     28                 q.push(crnt->right);
     29                 if (us.count(val)) crnt->right = nullptr;
     30             }
     31         }
     32 
     33         return res;
     34     }
     35 };