Created
December 6, 2017 08:07
-
-
Save klondaiker/83ad9cd85d598d19bc1b7294c47ca824 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
require 'active_support/core_ext/object/blank' | |
Category = Struct.new(:id, :children) | |
tree = [ | |
Category.new( | |
1, | |
[ Category.new(2, []), Category.new(3, []) ] | |
), | |
Category.new( | |
4, | |
[Category.new(5, [ Category.new(6, [])])] | |
), | |
Category.new( | |
7, | |
[] | |
) | |
] | |
def traverse(tree) | |
result = [] | |
stack = tree | |
while stack.present? | |
el = stack.pop | |
p el.id | |
if el.children.present? | |
el.children.each do |child| | |
stack << child | |
end | |
end | |
result << el.id | |
end | |
result.reverse | |
end | |
p traverse(tree) | |
#=> [2, 3, 1, 6, 5, 4, 7] |
Это итеративный подход со стеком, c рекурсией сложнее намного решение
а, я понял ж)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Все хорошо, только рекурсии нет, это же дерево, оно может иметь ветки на любую глубину ;)