lab2
parent
b9ffeb8d0d
commit
dbd1dfe45d
@ -0,0 +1,46 @@
|
||||
class BinarySearchTree
|
||||
include Enumerable
|
||||
|
||||
class Node
|
||||
attr_accessor :student, :left, :right
|
||||
|
||||
def initialize(student)
|
||||
@student = student
|
||||
@left = nil
|
||||
@right = nil
|
||||
end
|
||||
end
|
||||
|
||||
def initialize
|
||||
@root = nil
|
||||
end
|
||||
|
||||
def add(student)
|
||||
@root = insert(@root, student)
|
||||
end
|
||||
|
||||
def each(&block)
|
||||
in_order_traversal(@root, &block)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def insert(node, student)
|
||||
return Node.new(student) if node.nil?
|
||||
|
||||
if student.birth_date < node.student.birth_date
|
||||
node.left = insert(node.left, student)
|
||||
else
|
||||
node.right = insert(node.right, student)
|
||||
end
|
||||
node
|
||||
end
|
||||
|
||||
def in_order_traversal(node, &block)
|
||||
return if node.nil?
|
||||
|
||||
in_order_traversal(node.left, &block)
|
||||
yield node.student
|
||||
in_order_traversal(node.right, &block)
|
||||
end
|
||||
end
|
Loading…
Reference in new issue