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

twitter logo github logo ・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 Jan 28

Do you have any energy and time for your personal goals after a full day of work at your job?

Kaitian Xie profile image

dev.to is where software developers stay in the loop and avoid career stagnation.

Sign up (for free)