Created
March 8, 2012 22:04
-
-
Save jelder/2003754 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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