I have the following code, and was wondering if someone can tell me why, after running it, the value of @left_child
and @right_child
are still nil.
I think I know why, but I am asking for confirmation to the community. Also, is there a way I can make this work in a way like this?
module BinaryTree
class Node
attr_accessor :left_child, :right_child
def initialize(value)
@value = value
@left_child = nil
@right_child = nil
end
def add_child(value)
if value > @value
create_child(value, @right_child)
else
create_child(value, @left_child)
end
end
private
def create_child(value, which_child)
if which_child.nil?
which_child = Node.new(value)
else
which_child.add_child(value)
end
end
end
end
node = BinaryTree::Node.new(50)
node.add_child(20)
node.left_child # => nil
node.add_child(70)
node.right_child # => nil