DEV Community

Kaitian Xie
Kaitian Xie

Posted on • Edited on

2 2

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay