解题思路:
(1)后序遍历,将删除节点置空
(2)存储删除节点的左右子节点
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
vector<TreeNode*> v;
public:
bool helper(vector<int>& to_delete,int val) {
auto it=find(to_delete.begin(),to_delete.end(),val);
if(it!=to_delete.end()) return true;
else return false;
}
void postorder(TreeNode *root,vector<int>& to_delete) {
if(!root) return;
postorder(root->left,to_delete);
postorder(root->right,to_delete);
if(root->left!=NULL && helper(to_delete,root->left->val)) root->left=NULL;
if(root->right!=NULL && helper(to_delete,root->right->val)) root->right=NULL;
if(helper(to_delete,root->val)) {
if(root->left) v.push_back(root->left);
if(root->right) v.push_back(root->right);
}
return;
}
vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {
TreeNode* lac = new TreeNode(to_delete[0]);
lac->left=root;
postorder(lac,to_delete);
return v;
}
};