Solution without recursion in Ruby
def same? top_t1, top_t2
for_chek << [top_t1, top_t2] # (1) put task for check into queue
while t1,t2 = for_check.shift # (2)
return false unless t1.children.count == t2.children.count # generally for non-binary tree, but also needed for controlling of nil children
break if t1.children.empty?
t1_children = t1.children.sort # this is sorted arrays
t2_children = t2.children.sort # of childrens
return false unless t1_children == t2_children # (3)
0.upto(t1_children.count - 1) do |i|
for_check << [t1_children[i], t2_children[i]] # put equivalent child pairs into queue
end
end
return true
end
Ruby syntax tips:
- (1) putting element into array:
arr << elem
; in this case for_check
is array of arrays
- (2) parallel assignment:
t1,t2 = [item1, item2]
. Same as arr = [item1, item2]; t1 = arr[0]; t2 = arr[1]
- (3)
t1_children == t2_children
assumed corresponding behavior of == for this kind of objects. More verbose will be t1_children.map { |el| el.val } == t2_children.map { |el| el.val }
- here map
produces array of vals.