I have n-ary tree of game objects. The user randomly selects some objects in a tree and wants to delete. Problem is that some objects are children of the another. It turns out after each deletion of the node inside the hierarchy I must iterate through all selected nodes and remove it. Is the algorithm faster than O (n^2)?
Upd: to make it more clear what I need, I wrote pseudocode:
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);
}