I'm implementing a binary search tree in ruby, and I'm attempting to define a function to remove an value from the tree. The Tree has a @root value that points to a Node object. which is defined as such:
class Node
attr_reader :value
attr_accessor :left, :right
def initialize value=nil
@value = value
@left = nil
@right = nil
end
# Add new value as child node to self, left or ride
# allows for duplicates, to L side of tree
def insert new_value
if new_value <= @value
@left.nil? ? @left = Node.new(new_value) : @left.insert(new_value)
elsif new_value > @value
@right.nil? ? @right = Node.new(new_value) : @right.insert(new_value)
end
end
end
Thus, the nodes all hold references to their L & R children. Everything works on the tree, inserting, traversing, performing a breadth-first-search (level-order-traverse) to return a Node value, if found.
The problem I'm having is when trying to remove a Node object. I can't figure out how to set the actual OBJECT to nil, or to its child, for example, rather than reassigning a POINTER/variable to nil and the object still existing.
Tree has two functions that are supposed to do this (you can assume that breadth_first_search correctly returns the appropriate found node, as does smallest_r_child_of)
def remove value
node = breadth_first_search(value)
return false if node.nil?
remove_node(node)
end
def remove_node node
if node.left.nil? && node.right.nil?
node = nil
elsif !node.left.nil? && node.right.nil?
node = node.left
elsif node.left.nil? && !node.right.nil?
node = node.right
else
node = smallest_r_child_of(node)
end
return true
end
I thought that by passing in the actual node object to remove_node, that I could call node = ____ and the like to reassign the actual object to something else, but all it does, as far as I can tell, is reset the node argument variable/pointer, while not actually reassigning my data at all.
Does anyone have any tips/suggestions on how to accomplish what I'm trying to do?
nodehas zero impact on the caller. Everything you do inremove_modemanipulates a local variable and does nothing to thenodeinside ofremove(value).