Count function on tree structure (non-binary)

Posted by Spevy on Programmers See other posts from Programmers or by Spevy
Published on 2012-10-12T14:08:48Z Indexed on 2012/10/12 15:48 UTC
Read the original article Hit count: 275

Filed under:
|

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, or language. I am sure I can adjust the example to fit my specific needs.

EDIT: I am curious about an example, rather than instructions or discussion. I know this is not technically difficult...

© Programmers or respective owner

Related posts about data-structures

Related posts about trees