Skip to content

Instantly share code, notes, and snippets.

@Bartuz
Last active December 6, 2015 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bartuz/a58d7660980b7c008d62 to your computer and use it in GitHub Desktop.
Save Bartuz/a58d7660980b7c008d62 to your computer and use it in GitHub Desktop.
class BinaryTree
attr_accessor :root
def initialize
@root = Node.new
end
def insert(letter, path)
node = root
path.each_char do |direction|
node = node.public_send(direction)
end
node.letter = letter
end
end
class Node
include Enumerable
attr_accessor :letter, :parent
attr_writer :l, :r
def initialize(parent = nil, letter = nil)
@parent = parent
@letter = letter
end
def l
@l ||= Node.new(self)
end
def l?
!@l.nil?
end
def r
@r ||= Node.new(self)
end
def r?
!@r.nil?
end
def each(&block)
l.each(&block) if l?
block.call(self)
r.each(&block) if r?
end
def <=>(other_node)
return -1 if l? || r?
word <=> other_node.word
end
def to_s
word
end
def word
parent.nil? ? letter : letter + parent.word
end
end
tree = BinaryTree.new
begin
while (input = gets.chomp)
letter, path = input.split
next if letter.nil?
path ||= ""
tree.insert(letter, path.downcase)
end
rescue Interrupt
puts tree.root.max.word
end
@Bartuz
Copy link
Author

Bartuz commented Dec 6, 2015

to run:
$ ruby z2.rb
input:

a LL
d 
a R
s L
ctrl-c
=> ASD

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment