I need to create two binary search trees in Ruby One using r
I need to create two binary search trees in Ruby. One using recursion. One using iteration. I\'m new to programming so I don\'t understand the differences between the two and could use some help getting started with these two programs.
Solution
For recursive:
def insert_rec(node, value)
if node.nil?
return Node.new(value, nil, nil)
elsif value < node.value
node.left ||= insert_rec(node.left, value)
elsif value > node.value
node.right ||= insert_rec(node.right, value)
else
# TODO return?
end
end
for iteration:
class Node
def initialize(name, nodes
@name = name
@nodes = nodes
end
end
class Iterator
def initialize(node)
@node = node
end
def next
???
end
end
In recursion, function call itself until the base condition is reached whereas iteration means repetition of process until the condition fails.
