def level_order(root)
return [] if not root
queue, result = [root], []
while queue.size > 0
result << queue.map(&:val)
queue = queue.map { node [node.left, node.right] }.flatten.compact # Can this assignment be omitted?
end
result
end
7 Lines solution in Ruby, can be more concise ?

def level_order(root) return [] if not root queue, result = [root], [] while !queue.empty? result << queue.map(&:val) #queue = queue.flat_map { node [node.left, node.right] }.compact ##Alter? queue.map! { node [node.left, node.right] }.flatten!.compact! end result end
Thanks to @StefanPochmann, do you mean this ?

Yes, those are two possibilities. In each of those, you could also do
[node.left, node.right].compact
instead, saving a!
in the second version.And I just realized that
while queue.any?
is not just shorter but also allows removing thereturn [] if not root
:def level_order(root) queue, result = [root], [] while queue.any? result << queue.map(&:val) queue.map! { node [node.left, node.right].compact }.flatten! end result end
(Btw, writing "@StefanPochmann" doesn't notify me, I only saw your answer by chance. If you want someone to be notified, better reply below where they wrote (I think most people leave the "email me if a comment is added after mine" checked))