Created
September 29, 2018 22:51
-
-
Save monorkin/9ac77bc10108dd9771de603688cfaa6a 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
# return the array containing the tree levels, from root to last level. | |
def tree_by_levels(node) | |
return [] unless node | |
unpacked_tree = {} | |
breadth_first_search(node, unpacked_tree) | |
unpacked_tree.values.flatten | |
end | |
def breadth_first_search(node, hash = {}, depth = 0) | |
return unless node | |
hash[depth] ||= [] | |
hash[depth] << node.value | |
breadth_first_search(node.left, hash, depth + 1) | |
breadth_first_search(node.right, hash, depth + 1) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment