Skip to content

Instantly share code, notes, and snippets.

@janester
Created August 7, 2013 00:28
Show Gist options
  • Save janester/6170181 to your computer and use it in GitHub Desktop.
Save janester/6170181 to your computer and use it in GitHub Desktop.
binary tree example for WDI-SF-MAY
require "pry"
require "pry-debugger"
require "pry-stack_explorer"
class Node
attr_accessor :data, :nxt, :prv
def initialize(data)
self.data = data
self.nxt = nil
self.prv = nil
end
def to_s
"prev:#{!self.prv.nil? ? self.prv.data : 'nil'} - #{self.data} - next:#{!self.nxt.nil? ? self.nxt.data : 'nil'}"
end
end
class Tree
attr_accessor :root
def insert(new_node, r=self.root)
if self.root.nil?
self.root = new_node
else
if r.data < new_node.data
if r.nxt.nil?
r.nxt = new_node
else
insert(new_node, r.nxt)
end
else
if r.prv.nil?
r.prv = new_node
else
insert(new_node, r.prv)
end
end
end
end
def find(name, r=self.root)
if r.data == name
return r
else
if r.data > name
if r.prv.nil?
puts "not found"
else
find(name, r.prv)
end
else
if r.nxt.nil?
puts "not found"
else
find(name, r.nxt)
end
end
end
end
def to_s
if self.root.nil?
"empty"
else
tree_list(self.root)
end
end
def tree_list(node)
name_list = []
if !node.prv.nil?
name_list << tree_list(node.prv)
end
name_list << node.data
if !node.nxt.nil?
name_list << tree_list(node.nxt)
end
return name_list
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment