class Solution {
vector<TreeNode*> res;
unordered_set<int> delete_set;
public:
vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {
delete_set.insert(to_delete.begin(), to_delete.end());
helper(root, true);
return res;
}
bool helper(TreeNode* &root, const bool& isAdd) {
if (root) {
if (delete_set.count(root->val)) {
if (helper(root->left, true)) root->left = nullptr;
if (helper(root->right, true)) root->right = nullptr;
return true;
}
if (isAdd) res.push_back(root);
if (helper(root->left, false)) root->left = nullptr;
if (helper(root->right, false)) root->right = nullptr;
}
return false;
}
};
移除链表元素
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
bool flag=false;
bool dfs(ListNode * head,int val){
if(head){
flag=dfs(head->next,val);
if(head->val==val){
if(flag){
head->next=head->next->next;
}
return true;
}
if(flag){
head->next=head->next->next;
}
return false;
}
else{
return false;
}
}
ListNode* removeElements(ListNode* head, int val) {
if(!head)return nullptr;
while( head && head->val == val){
head=head->next;
}
if(!head){return nullptr;}
ListNode *temp=head;
dfs(temp,val);
if(head->val == val) return nullptr;
return head;
}
};