Commit 84b475c
Changed files (3)
lib
data_structures
utility
spec
data_structures
lib/data_structures/binary_tree.rb
@@ -1,3 +1,5 @@
+require_relative "../utility/block_visitor"
+
class BinaryTree
def push(item)
if @root
@@ -17,6 +19,10 @@ class BinaryTree
@root.accept(visitor, traversal) if @root
end
+ def each(&block)
+ accept(BlockVisitor.new(&block))
+ end
+
class BinaryTreeNode
attr_reader :left, :right, :data
lib/utility/block_visitor.rb
@@ -0,0 +1,9 @@
+class BlockVisitor
+ def initialize(&block)
+ @block = block
+ end
+
+ def visit(item)
+ @block.call(item)
+ end
+end
spec/data_structures/binary_tree_spec.rb
@@ -13,11 +13,20 @@ describe BinaryTree do
end
context "when many items are pushed on to the tree" do
- it "should increase the size" do
+ before :each do
10.times do |n|
sut.push(n)
end
+ end
+
+ it "should increase the size" do
sut.size.should == 10
end
+
+ it "can iterate through each item" do
+ sut.each do |item|
+ item.should_not be_nil
+ end
+ end
end
end