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

twitter logo github logo Updated on ・1 min read

LeetCode in Ruby (11 Part Series)

1) LeetCode in Ruby: 70. Climbing Stairs 2) LeetCode in Ruby: 206 Reverse Linked List 3 ... 9 3) LeetCode in Ruby: 102. Binary Tree Level Order Traversal 4) LeetCode in Ruby: 107. Binary Tree Level Order Traversal II 5) LeetCode in Ruby: 70. Climbing Stairs 6) LeetCode in Ruby: 242. Valid Anagram 7) LeetCode in Ruby: 387. First Unique Character in a String 8) LeetCode in Ruby: 771 Jewels and Stones 9) LeetCode in Ruby: 56. Merge Intervals 10) LeetCode in Ruby: 26. Remove Duplicates from Sorted Array 11) LeetCode in Ruby: 62. Unique Paths


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?
    result << level


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

twitter logo DISCUSS
Classic DEV Post from Jun 1 '19

Demystifying Open Source Contributions

This quick guide is mainly for first-time contributors and people who want to start helping open sour...

Kaitian Xie profile image

Make better choices about your code and your career.

Create Your Account