I wrote the following Ruby implementation of a basic binary search tree.
I believe that rt = Node.new(data)
is not actually modifying the underlying object but is in fact just a temporary variable that is getting discarded.
#!/usr/bin/env ruby
class Node
attr_accessor :left, :right, :data
def initialize(d)
@left = nil
@right = nil
@data = d
end
end
class BST
attr_accessor :root
def initialize
@root = nil
end
def add_helper(rt, d)
if rt != nil
add_helper(rt.left, d) if d < rt.data
add_helper(rt.right, d) if d > rt.data
end
rt = Node.new(d)
end
def add(data)
add_helper(root, data)
end
def print_helper(rt)
return if rt == nil
pr(rt.left) if rt.left != nil
puts rt.data
pr(rt.right) if rt.right != nil
end
def print_tree
print_helper(root)
end
end
###########################
b = BST.new
b.add(5)
b.add(-10)
b.print_tree
What is wrong with my implementation? I know that I should debug, and I really have. I put print statements and eventually realized that everything, even the Node object itself, was still nil.