Can anyone please suggest me any pointer to an iterative algorithm for insertion and deletion into a Red-Black Tree? All the algorithms available in .Net/C# are based on recursion, which I can't trust for handling very large number of data (hence large number of recursion depth for insertion/deletion). Does anybody have one based on iteration?
Note : Goletas.Collection uses an iterative algorithm for AVL tree which is highly efficient for large number of data, I want similar thing for Red-Black Tree also.
- 2Since a Red-Black tree is balanced, the height of a tree with
Nelements in it is approximatelylog_2(N)(at most2*log_2(N+1)). Therefor recursive operations will not take that many steps even if your structure is very large. Of course, you haven't specified what "large" actually is (could you clarify that?). Also, have you tried using an existing implementation of a self balancing tree? If not, it would be a waste of time if you'd start implementing something that is not necessary to begin with.Bart Kiers– Bart Kiers2010-09-21 08:16:11 +00:00CommentedSep 21, 2010 at 8:16
3 Answers3
Tree-based algorithms are by their very nature recursive.
Of course youcould rewrite them to be iterative but that would be an exercise in futility. Here’s why:
Red-black trees and similar data structures areself-balanced and their height is logarithmic with the number of values stored. This means that you willnever hit the recursion ceiling – this would require that you insert ~ 22000 elements, which is simply not going to happen: your computer doesn’t have enough memory, and never, ever will.
– Stick with recursion, it’s fine.
2 Comments
Thanks everyone for your valuable comments. I just found one but in VB6 and C. I think its enough to grasp the idea. Here are the links
Hope someone will find it helpful. :)
1 Comment
There is a version inIntroduction To Algorithms by Thomas H Cormen, Charles E Leiserson, Ronald L Rivest, Clifford Stein.
The pseudo code is online available atGoogle books (page 270).
Like pointed out in the comments, the approach of copying the data to nodez instead of replacingz byy in line 14/15 is not optimal, especially if you have pointers to the nodes somewhere else. So line 13-16 can be instead:
do_fixup = y.color == BLACKif y is not z: replace_parent(tree, y, z) y.left = z.left y.left.parent = y y.right = z.right y.right.parent = y y.color = z.colorif do_fixup: ...Wherereplace_parent is defined as (this can be used for line 7-12, too):
def replace_parent(tree, a, b): a.parent = b.parent if not b.parent: tree.root = a else: if b is b.parent.left: b.parent.left = a else: b.parent.right = a6 Comments
Explore related questions
See similar questions with these tags.
