Skip to content

Instantly share code, notes, and snippets.

@shadeslayer
Created April 6, 2015 15:59
Show Gist options
  • Save shadeslayer/668336e9923a3d775027 to your computer and use it in GitHub Desktop.
Save shadeslayer/668336e9923a3d775027 to your computer and use it in GitHub Desktop.
class Node
include Enumerable
attr_accessor :left, :right, :data
def initialize(data)
@data = data
@left = nil
@right = nil
end
def each(&block)
left.each(&block) if left
block.call(self)
right.each(&block) if right
end
def <=>(other)
@data <=> other.data
end
def <=(other)
@data <= other.data
end
def >=(other)
@data >= other.data
end
end
class Tree
attr_accessor :root
def initialize(root)
@root = root
end
def insert(node)
insert_p(node, @root)
end
private
def insert_p(node, root)
if node <= root
if root.left.nil?
root.left = node
else
insert_p(node, root.left)
end
elsif node >= root
if root.right.nil?
root.right = node
else
insert_p(node, root.right)
end
end
end
end
a = Node.new(3)
b = Node.new(4)
c = Node.new(5)
t = Tree.new(a)
t.insert(b)
t.insert(c)
t.insert(Node.new(1))
p t
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment