LeetCode 1110. Delete Nodes And Return Forest
Given the root of a binary tree, each node in the tree has a distinct value.
After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).
Return the roots of the trees in the remaining forest. You may return the result in any order.
Example 1:
Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
Output: [[1,2,null,4],[6],[7]]
Example 2:
Input: root = [1,2,4,null,3], to_delete = [3]
Output: [[1,2,4]]
Constraints:
The number of nodes in the given tree is at most 1000.
Each node has a distinct value between 1 and 1000.
to_delete.length <= 1000
to_delete contains distinct values between 1 and 1000.
实现思路:
将一棵树按照要求删除一个结点变成一片森林,模拟操作即可,注意细节。
AC代码:
class Solution {
unordered_map<int,TreeNode*> mp;
unordered_map<int,TreeNode*> father;//保留父节点
bool vist[1010]= {false}; //是否是被删除的结点
public:
void dfs(TreeNode *root,TreeNode *fa) {
if(!root) return;
mp[root->val]=root;//保留结点
dfs(root->left,root);
dfs(root->right,root);
father[root->val]=fa;//保留父节点
}
vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {
dfs(root,nullptr);
for(int i=0; i<to_delete.size(); i++) {
int val=to_delete[i];
vist[val]=true;//当前结点已是被删除结点
if(father[val]) {//当父节点不为空的时候才处理
if(father[val]->left==mp[val]) father[val]->left=nullptr;//处理被删结点父节点
else father[val]->right=nullptr;
}
if(mp[val]->left) father[mp[val]->left->val]=nullptr;//将当前删除结点和其孩子结点断开
if(mp[val]->right) father[mp[val]->right->val]=nullptr;
}
vector<TreeNode*> ans;
for(auto it : father) {
if(vist[it.first]) continue;//如果是被删除的结点则不统计
if(it.second==nullptr) ans.push_back(mp[it.first]);
}
return ans;
}
};
方法二
后序遍历法
class Solution {//后序遍历法
public:
vector<TreeNode*> delNodes(TreeNode* root, vector<int>& toDelete) {
vector<TreeNode*> result;
unordered_set<int> worker;
for (int &i : toDelete) worker.insert(i);
delNodes(root, worker, result);
if (root) result.push_back(root);
return result;
}
private:
void delNodes(TreeNode* &root, unordered_set<int>& toDelete, vector<TreeNode*> &result) {
if (!root) return;
delNodes(root->left, toDelete, result);
delNodes(root->right, toDelete, result);
if (toDelete.count(root->val)) {
if (root->left) result.push_back(root->left);
if (root->right) result.push_back(root->right);
root = nullptr;
}
}
};