7 Lines solution in Ruby, can be more concise ?


  • 0
    A
    def level_order(root)
      return [] if not root
      queue, result = [root], []
      while queue.size > 0
        result << queue.map(&:val)
        queue = queue.map { |node| [node.left, node.right] }.flatten.compact   # Can this assignment be omitted?
      end
      result
    end

  • 0

    You could use queue.empty?. And queue.flat_map or queue.map!.


  • 0
    A
    def level_order(root)
      return [] if not root
      queue, result = [root], []
      while !queue.empty?
        result << queue.map(&:val)
        #queue = queue.flat_map { |node| [node.left, node.right] }.compact  ##Alter?
        queue.map! { |node| [node.left, node.right] }.flatten!.compact!
      end
      result
    end
    

    Thanks to @StefanPochmann, do you mean this ?


  • 0

    Yes, those are two possibilities. In each of those, you could also do [node.left, node.right].compact instead, saving a ! in the second version.

    And I just realized that while queue.any? is not just shorter but also allows removing the return [] if not root:

    def level_order(root)
      queue, result = [root], []
      while queue.any?
        result << queue.map(&:val)
        queue.map! { |node| [node.left, node.right].compact }.flatten!
      end
      result
    end
    

    (Btw, writing "@StefanPochmann" doesn't notify me, I only saw your answer by chance. If you want someone to be notified, better reply below where they wrote (I think most people leave the "email me if a comment is added after mine" checked))


  • 0
    A

    Yeah, I think your solution is the best one!


Log in to reply
 

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