Skip to content

Instantly share code, notes, and snippets.

@anthonynsimon
Last active April 7, 2016 09:33
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 anthonynsimon/42cdeb48adddfbcdc8fb00585c5d419d to your computer and use it in GitHub Desktop.
Save anthonynsimon/42cdeb48adddfbcdc8fb00585c5d419d to your computer and use it in GitHub Desktop.
Simple Binary Tree in Ruby
class Node
attr_accessor :value, :left, :right
def initialize(value=nil)
@value = value
end
end
class BinaryTree
attr_accessor :root, :num_loops
protected :root
def initialize
@num_loops = 0
end
def insert(value)
if @root == nil
@root = Node.new(value)
return
end
current = @root
while true do
@num_loops += 1
if current.value > value
if current.left == nil
current.left = Node.new value
break
end
current = current.left
else
if current.right == nil
current.right = Node.new value
break
end
current = current.right
end
end
end
def traverse
if @root == nil
return nil
end
traverse_worker(@root)
end
def traverse_worker(node)
if node == nil
return
end
if node.left
traverse_worker node.left
end
puts node.value
if node.right
traverse_worker node.right
end
end
def generate(list)
list.each do |value|
insert(value)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment