Skip to content

Instantly share code, notes, and snippets.

@genewoo
Last active January 4, 2016 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save genewoo/8542603 to your computer and use it in GitHub Desktop.
Save genewoo/8542603 to your computer and use it in GitHub Desktop.
BST Implement in Ruby
class BSTree
attr_accessor :left, :right, :parent, :value
def initialize(value, parent = nil)
@value = value
@parent = parent
end
def self.build_by_array(array, parent = nil)
return nil unless array
if array.length == 1
middle = 0
else
middle = ((array.length - 1) * 1.0 / 2).floor
end
bst = BSTree.new(array[middle], parent)
# p "-" * 10
# p middle
# p bst.value
# p "=" * 10
if (middle > 0)
# p "L"
# p array[0..middle - 1]
bst.left = BSTree.build_by_array(array[0..middle - 1], parent)
end
if (middle < array.length - 1)
# p "R"
# p array[middle + 1 .. - 1]
bst.right = BSTree.build_by_array(array[middle + 1 .. - 1], parent)
end
bst
end
def to_nested_a
[@value, [@left.nil? ? nil : @left.to_nested_a, @right.nil? ? nil : @right.to_nested_a]]
end
def to_hash
hash = {}
hash.merge!({ left: @left.to_hash }) if @left
hash.merge!({ right: @right.to_hash }) if @right
{@value => hash}
end
def to_a
(@left.to_a + [@value] + @right.to_a).flatten
end
def validate?
(@left.nil? || @left.value < @value && @left.validate?) \
&& (@right.nil? || @right.value > @value && @right.validate?)
end
def look_up(value)
if value == @value
return self
elsif value > @value
target = @right
else value < @value
target = @left
end
return target.look_up(value) if target
end
end
bst = BSTree.build_by_array((1..10).to_a)
puts bst.to_nested_a.inspect
puts bst.to_hash.inspect
puts bst.to_a == (1..10).to_a
puts bst.validate?
p bst.look_up(0)
p bst.look_up(10)
p bst.look_up(9)
p bst.look_up(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment