Permalink
Browse files

Make EmptyNode a subclass of Node

To reduce the same method definitions for Node and EmptyNode.
  • Loading branch information...
1 parent 81ad00b commit 40df91ddbd35d1c5f59aece778cd3075a7bc761e @nahi committed Mar 27, 2012
Showing with 62 additions and 79 deletions.
  1. +57 −63 lib/avl_tree.rb
  2. +5 −16 lib/red_black_tree.rb
View
@@ -4,69 +4,6 @@ class AVLTree
class Node
UNDEFINED = Object.new
- class EmptyNode
- def empty?
- true
- end
-
- def height
- 0
- end
-
- def value
- nil
- end
-
- def values
- []
- end
-
- def size
- 0
- end
-
- def each(&block)
- # intentionally blank
- end
-
- # returns new_root
- def insert(key, value)
- Node.new(key, value)
- end
-
- # returns value
- def retrieve(key)
- UNDEFINED
- end
-
- # returns [deleted_node, new_root]
- def delete(key)
- [self, self]
- end
-
- def dump_tree(io, indent = '')
- # intentionally blank
- end
-
- def dump_sexp
- # intentionally blank
- end
-
- def rotate
- self
- end
-
- def update_height
- # intentionally blank
- end
-
- # for debugging
- def check_height
- # intentionally blank
- end
- end
- EMPTY = Node::EmptyNode.new
-
attr_reader :key, :value, :height
attr_reader :left, :right
@@ -289,6 +226,63 @@ def collect
end
pool
end
+
+ class EmptyNode < Node
+ def initialize
+ @value = nil
+ @height = 0
+ end
+
+ def empty?
+ true
+ end
+
+ def size
+ 0
+ end
+
+ def each(&block)
+ # intentionally blank
+ end
+
+ # returns new_root
+ def insert(key, value)
+ Node.new(key, value)
+ end
+
+ # returns value
+ def retrieve(key)
+ UNDEFINED
+ end
+
+ # returns [deleted_node, new_root]
+ def delete(key)
+ [self, self]
+ end
+
+ def dump_tree(io, indent = '')
+ # intentionally blank
+ end
+
+ def dump_sexp
+ # intentionally blank
+ end
+
+ def rotate
+ self
+ end
+
+ def update_height
+ # intentionally blank
+ end
+
+ # for debugging
+ def check_height
+ # intentionally blank
+ end
+ end
+ EMPTY = Node::EmptyNode.new.freeze
+
end
DEFAULT = Object.new
View
@@ -377,27 +377,16 @@ def collect
pool
end
- class EmptyNode
- def red?
- false
- end
-
- def black?
- true
+ class EmptyNode < Node
+ def initialize
+ @value = nil
+ @color = :BLACK
end
def empty?
true
end
- def value
- nil
- end
-
- def values
- []
- end
-
def size
0
end
@@ -429,7 +418,7 @@ def dump_sexp
# intentionally blank
end
end
- EMPTY = Node::EmptyNode.new
+ EMPTY = Node::EmptyNode.new.freeze
end
DEFAULT = Object.new

0 comments on commit 40df91d

Please sign in to comment.