Skip to content

Instantly share code, notes, and snippets.

@gagaception
Last active October 22, 2015 08:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gagaception/afdfa4428a614eeb2b9d to your computer and use it in GitHub Desktop.
Save gagaception/afdfa4428a614eeb2b9d to your computer and use it in GitHub Desktop.
binary_tree
class BinaryTree
attr_accessor :value, :left, :right
def initialize (value)
@value = value
end
end
class SortBinaryTree
attr_accessor :root
def initialize (root = nil)
@root = BinaryTree.new(root)
end
def build_tree(array)
arr = Array.new()
array.each {|i| arr << insert_node(i)}
arr
end
def insert_node(value)
node = @root
if node.nil?
node = BinaryTree.new(value)
else
insert_sorted_node(node, value)
end
end
def insert_sorted_node (node, value)
if (value < node.value)
if node.left.nil?
node.left = BinaryTree.new(value)
else
insert_sorted_node(node.left, value)
end
elsif (node.value < value)
if (node.right.nil?)
node.right = BinaryTree.new(value)
else
insert_sorted_node(node.right,value)
end
else
return node
end
end
def binary_tree_output(array)
puts " "
array.each {|i| puts "parent - #{i.value if !i.nil?}; left: #{i.left.value if !i.left.nil?} right: #{i.right.value if !i.right.nil?}"}
end
end
given_array = [7, 4, 9, 1, 6, 14, 10]
root = given_array[0]
btree = SortBinaryTree.new(root)
btree_array = btree.build_tree(given_array)
btree.binary_tree_output(btree_array)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment