Probajte ovo:
Code (ruby):
def r_add t, e, max = nil
return e if t.nil?
if !t.is_a?(Array)
return false if max == 1
return [1, t, e]
end
if s = r_add(t[2], e, t[0])
return [t[0], t[1], s]
end
return false if t[0]*2 == max
return [t[0]*2, t, e]
end
my_tree = nil
[:a, :b, :c, :d, :e, :f, :g, :h, :i].each do |val|
my_tree = r_add my_tree, val
puts my_tree.inspect
end
$ ruby main.rb
:a
[1, :a, :b]
[2, [1, :a, :b], :c]
[2, [1, :a, :b], [1, :c, :d]]
[4, [2, [1, :a, :b], [1, :c, :d]], :e]
[4, [2, [1, :a, :b], [1, :c, :d]], [1, :e, :f]]
[4, [2, [1, :a, :b], [1, :c, :d]], [2, [1, :e, :f], :g]]
[4, [2, [1, :a, :b], [1, :c, :d]], [2, [1, :e, :f], [1, :g, :h]]]
[8, [4, [2, [1, :a, :b], [1, :c, :d]], [2, [1, :e, :f], [1, :g, :h]]], :i]
//edit: uprostio malo
//edit: i još malo, izbacio klasu da ne bi bunila narod
[Ovu poruku je menjao jablan dana 22.02.2010. u 20:13 GMT+1]