思路
采用的是类似后序遍历的方式对节点进行删除,理由是我们要先删除左子树和右子树中要删除的节点,再删除自己本身。
判断条件:有没有在to_delete中找到该节点
代码
Talk is cheap, show me the code
/**
* 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 {
public:
vector<TreeNode*> trees;
vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {
if(!root){
return trees;
}
root = deleteNodes(root, to_delete);
if(root)// 最后来判断有没有把root删掉了,没删掉的话要记得push_back(root)
trees.push_back(root);
return trees;
}
TreeNode* deleteNodes(TreeNode* root, vector<int>& to_delete) {
if(!root)
return NULL;
root->left = deleteNodes(root->left, to_delete); // 遍历左子树
root->right = deleteNodes(root->right, to_delete); // 遍历右子树
vector<int>::iterator it = find(to_delete.begin(), to_delete.end(), root->val); // 找到节点
if(it != to_delete.end()){ // 如果找到该root,那么删除
if(root->left)
trees.push_back(root->left); // 存在左子树才push back
if(root->right)
trees.push_back(root->right);// 存在右子树才push back
to_delete.erase(it); // 删除to_delete中的it(其实不删也没关系)
return NULL; // 节点被删除了就返回空
}
return root; // 正常返回
}
};