Accepted Ruby solution


  • 0
    G

    I went for the straight forward solution.

    def zigzag_level_order(root)
        if root.nil?
            return []
        end
        
        res = []
        curr_nodes = [root]
        is_reversed = false
        
        while curr_nodes.length > 0 do
           next_nodes = []
           curr_nodes.each do |node|
               if !node.left.nil?
                   next_nodes << node.left
               end
               if !node.right.nil?
                   next_nodes << node.right
               end
           end
           if is_reversed
               res << curr_nodes.map{|n|n.val}.reverse
           else
               res << curr_nodes.map{|n|n.val}
           end
           is_reversed = !is_reversed
           curr_nodes = next_nodes
        end
        res
    end
    

Log in to reply
 

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