Created
October 21, 2015 22:58
-
-
Save jfelipe/3a71b71bb752f9e8a129 to your computer and use it in GitHub Desktop.
Code wars "Sort binary tree by levels"
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 | |
result = [] | |
q = [node] | |
until q.empty? | |
node = q.shift | |
q << node.left if node.left | |
q << node.right if node.right | |
result << node.value | |
end | |
result | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks