Skip to content

Instantly share code, notes, and snippets.

@apeiros
Forked from CodePint/binary_tree.rb
Last active February 8, 2018 16:10
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 apeiros/f37bffe200ff63420f1794e0f5d25974 to your computer and use it in GitHub Desktop.
Save apeiros/f37bffe200ff63420f1794e0f5d25974 to your computer and use it in GitHub Desktop.
binary tree and nodes
class Node
attr_accessor :data, :left, :right
def initialize(data)
@left = nil
@right = nil
@data = data
end
include Comparable
def <=>(node)
data <=> node.data
end
def nodes
result = []
result.concat(@left.nodes) if @left
result << self
result.concat(@right.nodes) if @right
result
end
def insert(new_node)
if new_node < self
if @left
@left.insert(new_node)
else
@left = new_node
end
else
if @right
@right.insert(new_node)
else
@right = new_node
end
end
end
def to_s
[left, data, right].join(" ")
end
end
class BinaryTree
attr_accessor :root
def insert(new_node)
if @root
@root.insert(new_node)
else # if root (first node in tree) does not exist
@root = new_node #assign the new_node to root instance variable
end
end
def nodes
@root.nodes
end
#def to_s
# self.root.to_s.squeeze(" ").strip
#end
end
@tree = BinaryTree.new
%w(Dan Barry Ted Daniel Alice Andy Sally).each do |name|
@tree.insert(Node.new(name))
end
puts @tree.nodes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment