Advertisement
nikunjsoni

1110

Apr 24th, 2021
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  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. vector<TreeNode*> ans;
  14. unordered_map<int, bool> m;
  15. public:
  16.     vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {
  17.         for(int val: to_delete)
  18.             m[val] = true;
  19.         if(!m.count(root->val)) ans.push_back(root);
  20.         dfs(root, NULL);
  21.         return ans;
  22.     }
  23.    
  24.     void dfs(TreeNode* curr, TreeNode* parent){
  25.         if(!curr) return;
  26.         dfs(curr->left, curr);
  27.         dfs(curr->right, curr);
  28.        
  29.         // Delete the current node and add its left/right child to answer list.
  30.         if(m.count(curr->val)){
  31.             if(curr->left) ans.push_back(curr->left);
  32.             if(curr->right) ans.push_back(curr->right);
  33.             if(parent && parent->left == curr) parent->left = NULL;
  34.             if(parent && parent->right == curr) parent->right = NULL;
  35.             delete curr;
  36.         }
  37.     }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement