Skip to content

Instantly share code, notes, and snippets.

@jelder
Created March 8, 2012 22:04
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 jelder/2003754 to your computer and use it in GitHub Desktop.
Save jelder/2003754 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
class Node
attr_accessor :val, :left, :right
def initialize( val = nil )
@val = val
@left, @right = nil, nil
end
def insert( val )
if val < @val
if @left.nil?
@left = Node.new( val )
else
@left.insert( val )
end
elsif val > @val
if @right.nil?
@right = Node.new( val )
else
@right.insert( val )
end
else
return
end
end
def recursive_print
@left.recursive_print unless @left.nil?
print "#{@val} "
@right.recursive_print unless @right.nil?
end
def nonrecursive_print
stack = []
node = self
while true
while !node.nil?
stack << node
node = node.left
end
if !stack.empty?
node = stack.pop
print "#{node.val} "
node = node.right
else
break
end
end
end
end
puts "Input:"
node = Node.new(7)
(0..20).sort_by{ rand }.each do |val|
print "#{val} "
node.insert val
end
puts "\nPrinting recursively:"
node.recursive_print
puts "\nPrinting non-recursively:"
node.nonrecursive_print
puts ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment