Skip to content

Instantly share code, notes, and snippets.

@DimaSamodurov
Created October 29, 2012 15:45
Show Gist options
  • Save DimaSamodurov/3974281 to your computer and use it in GitHub Desktop.
Save DimaSamodurov/3974281 to your computer and use it in GitHub Desktop.
Build hash style tree from array of nodes.
# Got from: http://stackoverflow.com/questions/8028211/tree-to-array-algorithm-ruby
def build_tree(i, edges)
list = {}
out_nodes = edges.select {|e| e[0] == i}.map {|e| e[1]}.uniq
out_nodes.each {|n| list[n] = build_tree(n, edges)}
list
end
edges = [[1,2],[1,6],[1,9],[2,3],[3,10],[4,7]]
puts build_tree(1, edges)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment