I am implementing a tree Data structure in c# based (largely on Dan Vanderboom’s Generic implementation). I am now considering approach on handling a Count property which Dan does not implement.
The obvious and easy way would be to use a recursive call which Traverses the tree happily adding up nodes (or iteratively traversing the tree with a Queue and counting nodes if you prefer). It just seems expensive. (I also may want to lazy load some of my nodes down the road).
I could maintain a count at the root node. All children would traverse up to and/or hold a reference to the root, and update a internally settable count property on changes. This would push the iteration problem to when ever I want to break off a branch or clear all children below a given node. Generally less expensive, and puts the heavy lifting what I think will be less frequently called functions.
Seems a little brute force, and that usually means exception cases I haven’t thought of yet, or bugs if you prefer.
Does anyone have an example of an implementation which keeps a count for an Unbalanced and/or non-binary tree structure rather than counting on the fly? Don’t worry about the lazy load, I am sure I can adjust the example to fit my specific needs.
Thanks everyone for your comments. I didn’t really want to invite debate, just wanted to see if anyone had a sample, which seems not to be the case.
I think the answer is there isn’t a good sample available and I will need to do the work myself.
I’ve given each of you a +1 as you have all contributed to my conclusion.