Simple BFS solution in Ruby


  • 0
    G

    Want to share my solution using BFS:

    • push to results level by level,
    • only push child to next level if not nil.
    def level_order(root)
      return [] if root.nil?
      result = []
      q = [root]
      while !q.empty?
        # we only want values in the results
        result << q.map(&:val)
        next_lv = []
        q.each do |node|
          next_lv << node.left if node.left
          next_lv << node.right if node.right
        end
        q = next_lv
      end
      result 
    end
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.