Created
May 14, 2011 20:55
-
-
Save ksykulev/972623 to your computer and use it in GitHub Desktop.
Directory of files by level
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The goal is to traverse a tree and return an array A[0...h], where h is the height | |
# of the tree and A[i] is an array of items at height i. | |
# example: | |
# tree -> | |
# 0 | |
# 1 2 | |
# 3 4 5 6 | |
# 7 8 9 10 11 12 13 14 | |
# | |
# should give you: | |
# [[0], [1, 2], [3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13, 14]] | |
class MyTree | |
attr_accessor :children, :value | |
def initialize(t) | |
@value = t.keys.first | |
@children = t[@value].map{ |child| MyTree.new(child) } | |
end | |
def by_depth | |
queue = [] | |
result = [] | |
height = 0 | |
queue << self | |
current_children = 1 | |
next_children = 0 | |
while( e = queue.slice!(0) ) | |
current_children -= 1 | |
if(result[height].is_a?(Array)) | |
result[height] << e.value | |
else | |
result[height] = [e.value] | |
end | |
if(!e.children.empty?) | |
queue = queue + e.children | |
next_children += e.children.count | |
end | |
if(current_children == 0) | |
height += 1 | |
current_children = next_children | |
next_children = 0 | |
end | |
end | |
result | |
end | |
end | |
example = {0 => [{1 => | |
[ {3 => [ | |
{7 => []}, {8 => []} | |
]}, | |
{4 => [ | |
{9 => []}, {10 => []} | |
]} | |
]}, | |
{2 => | |
[ {5 => [ | |
{11 => []}, {12 => []} | |
]}, | |
{6 => [ | |
{13 => []}, {14 => []} | |
]} | |
] | |
}] | |
} | |
tree = MyTree.new(example) | |
puts tree.by_depth.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment