Keeping track of the number of nodes in the subtree in black and red trees

algorithmsbinary treetrees

I was wondering, if I have a black and red tree and I want to keep track of the number of nodes in the subtree, what is the most effective way to do so?

I mean how do I work with these values while insertion, deletion and rotation of nodes, so that I don't have to process the number under every node again?

Best Answer

Allow me to expound a bit on @Robert's comment.

What you're talking about is caching a result that can be computed. Caching should be viewed as an optimization, the premature application of which is a known evil, which is to say: only do it at such time as you have a measurable performance issue. Caches easily go out of date, and making them 100% accurate will necessarily complicate the code. (And if you depend on them during the insert, update, rotate operations, you now have to have them up to date within those operations, not just between operations.) Caching can also make multi threaded code more complicated.

You can store the counts as @Robert suggests. You will have to reason which nodes' cached subtree count values need to change whenever an insert, delete, or rotation happens, and write code to update the cached counts. However, you can reason from count to count instead of fully recounting. So, when you insert at a parent, the parent's count goes up by one, you don't have to recount the other children; similarly, the parent's parent count also goes up by one (if you're doing transitive counting) etc... Rotation should have a more local effect, and not bubble up thru all the parents.

Because with inserts and deletes, the count adjustment necessarily has to be made up thru the parents all the way to the root, this will have some negative performance impact, sometimes due to processor memory cache misses incurred when visiting parents that wouldn't have otherwise been visited. Having performance tests would be a good idea, so that the caching and non-caching versions can be compared.

Related Topic