Permalink
Browse files

add example of using binary search tree

  • Loading branch information...
1 parent 5ff3612 commit 06ee90ef2cce7688ecf6df17dab128b5e4b3f2bd @samnang committed Feb 24, 2011
Showing with 41 additions and 4 deletions.
  1. +37 −0 binary_search_tree/examples/example1.rb
  2. +4 −4 binary_search_tree/lib/binary_search_tree/node.rb
@@ -0,0 +1,37 @@
+$:.unshift File.expand_path('../../lib', __FILE__)
+
+require 'binary_search_tree'
+require 'pp'
+
+class Student
+ include Comparable
+
+ attr_accessor :id, :name
+
+ def initialize(id, name)
+ @id = id
+ @name = name
+ end
+
+ def <=>(other)
+ @id <=> (other.respond_to?(:id) ? other.id : other)
+ end
+end
+
+student_tree = BinarySearchTree.new
+
+# Add value into tree
+(1..1000).to_a.shuffle.each do |id|
+ student_tree << Student.new(id, "Student name#{id}")
+end
+
+# Chainable adding style
+student_tree << Student.new(1010, "Student name1010") << Student.new(1005, "Student name1005")
+
+# Get student in the tree
+pp student_tree[90].value
+pp student_tree.find(90).value
+
+# Remove student in the tree
+student_tree.delete(1005)
+student_tree[90].delete
@@ -32,7 +32,7 @@ def add(value)
def find(value)
return self if @value == value
- branch = left_side?(value) ? left : right
+ branch = right_side?(value) ? right : left
branch.find(value) if branch
end
@@ -51,11 +51,11 @@ def delete
private
def find_side(value)
- left_side?(value) ? :left : :right
+ right_side?(value) ? :right : :left
end
- def left_side?(value)
- value < @value
+ def right_side?(value)
+ @value < value
end
def delete_when_no_child

0 comments on commit 06ee90e

Please sign in to comment.