DEV Community

Kaitian Xie
Kaitian Xie

Posted on • Updated on

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

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:

Top comments (1)

Collapse
 
enowmbi profile image
Enow B. Mbi

You deserve an oscar for clean code. thanks.