2024-07-17
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.
用 DFS 走
碰到要删的删掉
如果没有 parent 而且没有要删
就塞进 result
跟解答比起来
用 loop 找 delete 比直接 vector 操作慢了
dfs return bool 再处理也会比直接 return node 多一层判断
应该是这两个在慢吧
/**
* 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) {
vector<TreeNode*> results;
dfs(root, to_delete, results, false);
return results;
}
private:
bool dfs(TreeNode* root, vector<int>& to_delete, vector<TreeNode*>&
results, bool isChild) {
if (!root) {
return false;
}
bool delete_this = false;
for (int d : to_delete) {
if (root->val == d) {
delete_this = true;
break;
}
}
if (!isChild && !delete_this) {
results.push_back(root);
}
if (dfs(root->left, to_delete, results, !delete_this)) {
root->left = NULL;
}
if (dfs(root->right, to_delete, results, !delete_this)) {
root->right = NULL;
}
return delete_this;
}
};