Skip to content

Instantly share code, notes, and snippets.

@worace
Created February 11, 2016 23:00
Show Gist options
  • Save worace/ea264e897d35cc6970d8 to your computer and use it in GitHub Desktop.
Save worace/ea264e897d35cc6970d8 to your computer and use it in GitHub Desktop.
class BinaryTree
def initialize(data = nil)
@data = data
end
def left
@left ||= BinaryTree.new
end
def right
@right ||= BinaryTree.new
end
def insert(data)
if @data.nil?
@data = data
elsif data < @data
left.insert(data)
else
right.insert(data)
end
end
def include?(data)
if @data.nil?
false
elsif data == @data
true
elsif data < @data
left.include? data
else
right.include? data
end
end
def all
if @data.nil?
[]
else
left.all + [@data] + right.all
end
end
def count
if @data.nil?
0
else
1 + left.count + right.count
end
end
# health(0)
def health(desired_depth, current_depth = 0, total_count = count)
if @data.nil?
[]
elsif desired_depth == current_depth
[[data, count, count.to_f / total_count]]
else
left.health(desired_depth, current_depth + 1, total_count) +
right.health(desired_depth, current_depth + 1, total_count)
end
end
end
bt = BinaryTree.new
bt.insert(5)
puts bt.data
bt.insert(4)
bt.insert(7)
puts bt.left.data
puts bt.right.data
puts bt.include? 5
puts bt.include? 4
puts bt.include? 7
puts bt.include? 21
puts bt.all.inspect
puts bt.count
puts bt.health(0).inspect
puts bt.health(1).inspect
(1..10).to_a.shuffle.each do |i|
bt.insert(i)
end
puts bt.health(2).inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment