Zeuthen: Writing a C library, part 1
Posted Jun 29, 2011 23:51 UTC (Wed) by
njs (guest, #40338)
In reply to:
Zeuthen: Writing a C library, part 1 by MisterIO
Parent article:
Zeuthen: Writing a C library, part 1
The slightly inefficient way is to just do something like
while (there are nodes left) {
current_node = root;
while (has_children(current_node))
current_node = first_undeleted_child(current_node);
delete(current_node);
}
That deletes everything, needs no heap storage, and it's O(n (log n)^2), not so bad.
The more efficient way is to just preallocate a vector whose length is the same as your maximum tree height (resizing when necessary), and then in the destructor use it as the stack for a single-pass depth-first traversal. The extra memory required is pretty trivial. Not sure if it's worth the bother, though.
Well, honestly I'm not sure that any of this is worth the bother. It's a nice puzzle to handle this sort of thing properly in a classic data structure with perfect encapsulation from the rest of the program, but in real life it doesn't help until you've solved a whole pile of harder and idiosyncratic problems too.
(
Log in to post comments)