Note: (Partially note to self) This probably isn't the fully best way to do this, the validation method should validate behavior rather than class. I should write more about that.
My first thought upon seeingFirst off, I think that BST
isn't that great of a name for this class is. I'd go with Tree
, because that is what it isn't really necessarystores. In a binary search tree
Anyways, it's sufficientfirst thing first: I'd make it possible to keep track ofpass root
to the rootinitializer by making it an argument with a default value:
def initialize(root = nil)
@root = root
end
Next thing's next: The #insert
method!
I notice that you're checking if self.root
is nil
. In ruby, then the root refersthere's a slightly faster (IIRC) and much more ruby way of doing this: self.root.nil?
. It's a neat, built-in nil check. In addition, there's no reason to everything elsemodify @root
using its accessor, you can actually just modify it directly.
ButAlso, I will trynoticed that wherever you return a value, you're either returning the root, or the node that was passed in. I also note that you're always setting the node that was passed in as the root. So, you're actually always comparing to understand how you've done thisroot. With that in mind, here are some little bits of cleanup (incomplete, I'll come back and howfinish it can be improved.):
def insert(value, node)
# When this occurs, it will set @root.value == node.value
@root = Node.new(value) if @root.nil?
return @root if @root.value == value
if node.value > value
if node.left_child.nil?
node.left_child = Node.new(value)
else
insert(value, node.left_child)
end
else
if node.right_child.nil?
node.right_child = Node.new(value)
else
insert(value, node.right_child)
end
end
return node
end
Other notes
Here's an interesting example of how someone else implemented BSTs in ruby