Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Perf improvement for insert

Do red pull-up check and rotation at a time.
  • Loading branch information...
commit b0edf46b5e6c23147eeafb8325bffe19a470afc7 1 parent d0168e0
@nahi authored
Showing with 22 additions and 25 deletions.
  1. +22 −25 lib/red_black_tree.rb
View
47 lib/red_black_tree.rb
@@ -66,18 +66,16 @@ def insert(key, value)
ret = self
case key <=> @key
when -1
- check_red_pullup
@left = @left.insert(key, value)
- if black?
- ret = check_rotate_right
+ if black? and @left.red? and !@left.children_both_black?
+ ret = rebalance_for_left_insert
end
when 0
@value = value
when 1
- check_red_pullup
@right = @right.insert(key, value)
- if black?
- ret = check_rotate_left
+ if black? and @right.red? and !@right.children_both_black?
+ ret = rebalance_for_right_insert
end
end
ret
@@ -308,35 +306,34 @@ def rotate_right
private
- def check_red_pullup
- if black? and @left.red? and @right.red?
+ # trying to rebalance when the left sub-tree is 1 level higher than the right
+ def rebalance_for_left_insert
+ ret = self
+ if @right.red?
@color = :RED
@left.color = @right.color = :BLACK
- end
- end
-
- def check_rotate_right
- if @left.red?
- if @left.left.red?
- return rotate_right
- elsif @left.right.red?
+ else
+ if @left.right.red?
@left = @left.rotate_left
- return rotate_right
end
+ ret = rotate_right
end
- self
+ ret
end
- def check_rotate_left
- if @right.red?
- if @right.right.red?
- return rotate_left
- elsif @right.left.red?
+ # trying to rebalance when the right sub-tree is 1 level higher than the left
+ def rebalance_for_right_insert
+ ret = self
+ if @left.red?
+ @color = :RED
+ @left.color = @right.color = :BLACK
+ else
+ if @right.left.red?
@right = @right.rotate_right
- return rotate_left
end
+ ret = rotate_left
end
- self
+ ret
end
def delete_self
Please sign in to comment.
Something went wrong with that request. Please try again.