Commit d44e57b

mo khan <mo@mokhan.ca>
2013-07-13 16:14:43
start construction of a binary tree
1 parent 967cdf2
Changed files (3)
lib
data_structures
spec
lib/data_structures/binary_tree.rb
@@ -0,0 +1,60 @@
+class BinaryTree
+  def push(item)
+    if @root
+      @root.push(item)
+    else
+      @root = BinaryTreeNode.new(item) unless @root
+    end
+  end
+
+  def size
+    visitor = TotalCountVisitor.new
+    accept(visitor)
+    visitor.result
+  end
+
+  def accept(visitor)
+    @root.accept(visitor) if @root
+  end
+
+  class BinaryTreeNode
+    def initialize(data)
+      @data = data
+    end
+
+    def push(item)
+      if (item <=> @data) == -1
+        if @left
+          @left.push(item)
+        else
+          @left = BinaryTreeNode.new(item)
+        end
+      else
+        if @right
+          @right.push(item)
+        else
+          @right = BinaryTreeNode.new(item)
+        end
+      end
+    end
+
+    def accept(visitor)
+      visitor.visit(self)
+      @left.accept(visitor) if @left
+      @right.accept(visitor) if @right
+    end
+
+  end
+
+  class TotalCountVisitor
+    attr_reader :result
+    def initialize
+      @result = 0
+    end
+
+    def visit(item)
+      p item
+      @result += 1
+    end
+  end
+end
spec/data_structures/binary_tree_spec.rb
@@ -0,0 +1,23 @@
+require "spec_helper"
+
+#Tree data structure
+#each node has at most two children
+#nodes with children are parent nodes.
+describe BinaryTree do
+  let(:sut) { BinaryTree.new }
+
+  context "when there are no items in the tree" do
+    it "should have a size of 0" do
+      sut.size.should == 0
+    end
+  end
+
+  context "when many items are pushed on to the tree" do
+    it "should increase the size" do
+      10.times do |n|
+        sut.push(n)
+      end
+      sut.size.should == 10
+    end
+  end
+end
spec/spec_helper.rb
@@ -6,3 +6,4 @@ require_relative '../lib/sorting/merge_sort'
 
 require_relative '../lib/data_structures/linked_list_stack'
 require_relative '../lib/data_structures/dynamic_array_stack'
+require_relative '../lib/data_structures/binary_tree'