📅  最后修改于: 2023-12-03 15:22:02.696000             🧑  作者: Mango
在通用树或N元树中删除所有叶节点是一个常见的操作。下面给出C++实现:
#include <iostream>
#include <vector>
using namespace std;
class TreeNode {
public:
int val;
vector<TreeNode*> children;
TreeNode(int val) : val(val) {};
};
TreeNode* deleteLeaves(TreeNode* root) {
if (!root) return NULL;
if (root->children.empty()) {
delete root;
return NULL;
}
for (auto& child : root->children) {
child = deleteLeaves(child);
}
root->children.erase(
remove_if(
root->children.begin(),
root->children.end(),
[](TreeNode* child){ return !child; }
),
root->children.end()
);
if (root->children.empty()) {
delete root;
return NULL;
}
return root;
}
int main() {
TreeNode* root = new TreeNode(1);
TreeNode* child1 = new TreeNode(2);
TreeNode* grandchild1 = new TreeNode(3);
TreeNode* grandchild2 = new TreeNode(4);
TreeNode* child2 = new TreeNode(5);
TreeNode* grandchild3 = new TreeNode(6);
TreeNode* grandchild4 = new TreeNode(7);
root->children.push_back(child1);
child1->children.push_back(grandchild1);
child1->children.push_back(grandchild2);
root->children.push_back(child2);
child2->children.push_back(grandchild3);
child2->children.push_back(grandchild4);
root = deleteLeaves(root);
delete root;
return 0;
}
这里给出函数deleteLeaves
的实现。如果节点为空,则直接返回空指针;如果节点没有子节点,则删除这个节点并返回空指针。否则,依次递归删除子节点,并从子节点列表中删除空指针。最后,如果节点没有子节点,则删除这个节点并返回空指针。最终,函数返回根节点。
这段代码的时间复杂度为$O(N)$,其中$N$为节点数。空间复杂度为$O(H)$,其中$H$为树的高度。