BFS Ruby solution


  • 0
    T
    def vertical_order(root)
      return [] if root.nil?
      row = [[root, 0]]
      col_hash = {}
      while row.count > 0
        new_row = []
        row.each do |node, col|
          next if node.nil?
          col_hash[col] ||= []
          col_hash[col] << node.val
          new_row << [node.left, col-1] << [node.right, col+1]
        end
        row = new_row
      end
      (col_hash.keys.sort).map {|col| col_hash[col]}
    end
    

Log in to reply
 

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