题目
分析
解决tree的问题, 一般考虑使用递归,根据不同的题目,可以选择不同的遍历方式(前序,中序,后序遍历),本题可以使用后序遍历,最后处理根节点, 先分别处理每个节点的左子树,右子树
流程
使用后序遍历,观察每一个节点是否需要被删除,如果需要删除,保存该节点的左右子树(如果存在的话),不需要删除直接返回。
代码
python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def delNodes(self, root, to_delete):
"""
:type root: TreeNode
:type to_delete: List[int]
:rtype: List[TreeNode]
"""
ds = set(to_delete)
ans = []
def process(n):
if not n: return
n.left, n.right = process(n.left), process(n.right)
if n.val not in ds: return n
if n.left: ans.append(n.left)
if n.right: ans.append(n.right)
return None
root = process(root)
if root: ans.append(root)
return ans
c++版
/**
* 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*> delNodes(TreeNode* root, vector<int>& to_delete) {
if(!root)
return {};
vector<TreeNode*> result;
vector<TreeNode*> forest;
process(root, to_delete, result);
if(find(to_delete.begin(), to_delete.end(), root->val) == to_delete.end())
{
forest.push_back(root);
}
for(auto i:result) forest.push_back(i);
return forest;
}
TreeNode* process(TreeNode* root, vector<int>& to_delete, vector<TreeNode*>& result){
if(!root)
return NULL;
root->left= process(root->left, to_delete, result);
root->right = process(root->right, to_delete, result);
if(find(to_delete.begin(), to_delete.end(), root->val)!= to_delete.end())
{
if(root->left) result.push_back(root->left);
if(root->right) result.push_back(root->right);
return NULL;
}
return root;
}
};
知识点
find函数的使用
auto