2 Star 0 Fork 0

xinanXu/myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
LC1110.cpp 1.54 KB
一键复制 编辑 原始数据 按行查看 历史
xinanXu 提交于 2023-03-04 16:52 . 1110. 删点成林
/**
* 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*> ret;
set<int> s;
void Ord(TreeNode* root) {
if (!root) return;
if (s.find(root->val) != s.end()) {
root->val = 0;
if (root->left) ret.push_back(root->left);
if (root->right) ret.push_back(root->right);
}
Ord(root->left);
Ord(root->right);
}
void Del(TreeNode* root) {
if (!root) return;
auto t1 = root->left;
auto t2 = root->right;
if (t1 && !t1->val) root->left = nullptr;
if (t2 && !t2->val) root->right = nullptr;
Del(t1);
Del(t2);
}
void delVector() {
for (int i = 0; i < ret.size(); ) {
if (ret[i] && !ret[i]->val)
ret.erase(ret.begin() + i);
else i++;
}
}
vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {
int len = to_delete.size();
if (!root) return ret;
ret.push_back(root);
if (!len) return ret;
s = set<int>(to_delete.begin(), to_delete.end());
Ord(root);
Del(root);
delVector();
return ret;
}
};
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/DearAtri/myleetcode.git
git@gitee.com:DearAtri/myleetcode.git
DearAtri
myleetcode
myleetcode
master

搜索帮助