Skip to content

Instantly share code, notes, and snippets.

@jonathanpike
Last active December 7, 2015 00:43
Show Gist options
  • Save jonathanpike/3d2f28c25c078b2b5379 to your computer and use it in GitHub Desktop.
Save jonathanpike/3d2f28c25c078b2b5379 to your computer and use it in GitHub Desktop.
class BinaryTree
attr_accessor :payload, :left, :right
def initialize(payload, left, right)
@payload = payload
@left = left
@right = right
end
end
class BinaryTreeInsert
def create(array)
array.each do |item|
if item == array.first
@root = BinaryTree.new(item, nil, nil)
@current = @root
else
@current = @root
until item == @current.payload
if item > @current.payload && @current.right == nil
@current.right = BinaryTree.new(item, nil, nil)
elsif item < @current.payload && @current.left == nil
@current.left = BinaryTree.new(item, nil, nil)
elsif item > @current.payload && @current.right != nil
@current = @current.right
elsif item < @current.payload && @current.left != nil
@current = @current.left
end
end
end
end
end
def sort(node = @root)
return if (node == nil)
sort(node.left)
puts node.payload
sort(node.right)
end
end
array = [7, 4, 9, 1, 6, 14, 10]
tree = BinaryTreeInsert.new
tree.create(array)
tree.sort
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment