我有n个游戏对象树。用户随机选择树中的某些对象并要删除。问题在于某些对象是另一对象的子对象。事实证明,每次删除层次结构内的节点后,我都必须遍历所有选定的节点并将其删除。算法比O(n ^ 2)快吗?
更新:为了更加清楚我的需求,我编写了伪代码:
struct TreeNode
{
vector<TreeNode*> childs;
};
void removeNodeHierarchy(list<TreeNode*>& nodes, TreeNode *n)
{
for(TreeNode *child : n->childs())
removeNodeHierarchy(nodes, child);
nodes.remove(n); // complexity nodes.size()
delete n;
}
// The function I'm trying to write
// Problem: Total complexity = nodes.size() * nodes.size()
void removeNodes(list<TreeNode*>& nodes, TreeNode *root)
{
while (!nodes.empty()) // complexity nodes.size()
{
TreeNode *n = nodes.first();
removeNodeHierarchy(nodes, n);
}
}
void main()
{
TreeNode *tree = ...
list<TreeNode*> nodes = ...
removeNodes(nodes, tree);
}
答案 0 :(得分:0)
In order to search that node, it will take you O(n^d), where d is the depth of the tree. So it will be faster if d < 2 which I think will almost never be the case for a big game tree. Are you sure that n from n-ary and O(n^2) are the same symbol?