Given a binary tree, return the level order traversal of its nodes'
values. (ie, from left to right, level by level).
Given binary tree [3,9,20,null,null,15,7],
return its level order traversal as:
return  if root.nil?
arr = merge([level_order(root.left)], [level_order(root.right)]) #this returns an empty arr if both of those are nil..
def merge(arr1, arr2)
i = j = 0
while i < arr1.length && j < arr2.length
arr1[i] += arr2[j]
i += 1
j += 1
while j < arr2.length #check if any remaining elements in arr 2
arr1 << arr2[j]
j += 1
It should be as simple as changing this
arr = merge([level_order(root.left)], [level_order(root.right)])
arr = merge(level_order(root.left), level_order(root.right))
However I would have written this slightly differently:
input = [3,9,20,nil,nil,15,7] output =  start = 0 length = 1 while start < input.length do output << input.slice(start, length).compact start += length length *= 2 end puts output.inspect
This would avoid building a tree and would be more efficient than recursion.