loading...

LeetCode in Ruby: 107. Binary Tree Level Order Traversal II

algobot76 profile image Kaitian Xie Updated on ・1 min read

Iterative

def level_order(root)
  result = []
  return result if root.nil?

  queue = []
  queue << root

  until queue.empty?
    level_size = queue.length
    level = []
    level_size.times do
      node = queue.shift
      level << node.val
      queue << node.left unless node.left.nil?
      queue << node.right unless node.right.nil?
    end
    result << level
  end

  result.reverse!
end

This is very similar to the iterative solution for problem 102, except that we reverse result at the end. For detailed explanation, please read:

Discussion

pic
Editor guide
 

You deserve an oscar for clean code. thanks.